From a8e6f240eb84847e46bade87347f37488faa5cb7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:02:16 +0000 Subject: [PATCH 1/2] docs: Fix formatting of request arg in docstring chore: Update gapic-generator-python to v1.9.1 PiperOrigin-RevId: 518604533 Source-Link: https://github.com/googleapis/googleapis/commit/8a085aeddfa010af5bcef090827aac5255383d7e Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2ab4b0a0ae2907e812c209198a74e0898afcb04 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJhYjRiMGEwYWUyOTA3ZTgxMmMyMDkxOThhNzRlMDg5OGFmY2IwNCJ9 --- owl-bot-staging/v3/.coveragerc | 13 + owl-bot-staging/v3/.flake8 | 33 + owl-bot-staging/v3/MANIFEST.in | 2 + owl-bot-staging/v3/README.rst | 49 + owl-bot-staging/v3/docs/conf.py | 376 + owl-bot-staging/v3/docs/index.rst | 7 + .../v3/docs/resourcemanager_v3/folders.rst | 10 + .../docs/resourcemanager_v3/organizations.rst | 10 + .../v3/docs/resourcemanager_v3/projects.rst | 10 + .../v3/docs/resourcemanager_v3/services.rst | 11 + .../docs/resourcemanager_v3/tag_bindings.rst | 10 + .../v3/docs/resourcemanager_v3/tag_keys.rst | 10 + .../v3/docs/resourcemanager_v3/tag_values.rst | 10 + .../v3/docs/resourcemanager_v3/types.rst | 6 + .../google/cloud/resourcemanager/__init__.py | 177 + .../cloud/resourcemanager/gapic_version.py | 16 + .../v3/google/cloud/resourcemanager/py.typed | 2 + .../cloud/resourcemanager_v3/__init__.py | 178 + .../resourcemanager_v3/gapic_metadata.json | 813 ++ .../cloud/resourcemanager_v3/gapic_version.py | 16 + .../google/cloud/resourcemanager_v3/py.typed | 2 + .../resourcemanager_v3/services/__init__.py | 15 + .../services/folders/__init__.py | 22 + .../services/folders/async_client.py | 1724 ++++ .../services/folders/client.py | 1909 +++++ .../services/folders/pagers.py | 260 + .../services/folders/transports/__init__.py | 38 + .../services/folders/transports/base.py | 316 + .../services/folders/transports/grpc.py | 662 ++ .../folders/transports/grpc_asyncio.py | 661 ++ .../services/folders/transports/rest.py | 1650 ++++ .../services/organizations/__init__.py | 22 + .../services/organizations/async_client.py | 905 ++ .../services/organizations/client.py | 1096 +++ .../services/organizations/pagers.py | 139 + .../organizations/transports/__init__.py | 38 + .../services/organizations/transports/base.py | 219 + .../services/organizations/transports/grpc.py | 396 + .../organizations/transports/grpc_asyncio.py | 395 + .../services/organizations/transports/rest.py | 907 ++ .../services/projects/__init__.py | 22 + .../services/projects/async_client.py | 1779 ++++ .../services/projects/client.py | 1964 +++++ .../services/projects/pagers.py | 260 + .../services/projects/transports/__init__.py | 38 + .../services/projects/transports/base.py | 316 + .../services/projects/transports/grpc.py | 684 ++ .../projects/transports/grpc_asyncio.py | 683 ++ .../services/projects/transports/rest.py | 1676 ++++ .../services/tag_bindings/__init__.py | 22 + .../services/tag_bindings/async_client.py | 556 ++ .../services/tag_bindings/client.py | 754 ++ .../services/tag_bindings/pagers.py | 139 + .../tag_bindings/transports/__init__.py | 38 + .../services/tag_bindings/transports/base.py | 190 + .../services/tag_bindings/transports/grpc.py | 343 + .../tag_bindings/transports/grpc_asyncio.py | 342 + .../services/tag_bindings/transports/rest.py | 558 ++ .../services/tag_keys/__init__.py | 22 + .../services/tag_keys/async_client.py | 1249 +++ .../services/tag_keys/client.py | 1434 ++++ .../services/tag_keys/pagers.py | 139 + .../services/tag_keys/transports/__init__.py | 38 + .../services/tag_keys/transports/base.py | 274 + .../services/tag_keys/transports/grpc.py | 487 ++ .../tag_keys/transports/grpc_asyncio.py | 486 ++ .../services/tag_keys/transports/rest.py | 1299 +++ .../services/tag_values/__init__.py | 22 + .../services/tag_values/async_client.py | 1247 +++ .../services/tag_values/client.py | 1432 ++++ .../services/tag_values/pagers.py | 139 + .../tag_values/transports/__init__.py | 38 + .../services/tag_values/transports/base.py | 274 + .../services/tag_values/transports/grpc.py | 488 ++ .../tag_values/transports/grpc_asyncio.py | 487 ++ .../services/tag_values/transports/rest.py | 1301 +++ .../resourcemanager_v3/types/__init__.py | 160 + .../cloud/resourcemanager_v3/types/folders.py | 495 ++ .../resourcemanager_v3/types/organizations.py | 254 + .../resourcemanager_v3/types/projects.py | 584 ++ .../resourcemanager_v3/types/tag_bindings.py | 194 + .../resourcemanager_v3/types/tag_keys.py | 302 + .../resourcemanager_v3/types/tag_values.py | 304 + owl-bot-staging/v3/mypy.ini | 3 + owl-bot-staging/v3/noxfile.py | 184 + ...3_generated_folders_create_folder_async.py | 59 + ...v3_generated_folders_create_folder_sync.py | 59 + ...3_generated_folders_delete_folder_async.py | 56 + ...v3_generated_folders_delete_folder_sync.py | 56 + ...r_v3_generated_folders_get_folder_async.py | 52 + ...er_v3_generated_folders_get_folder_sync.py | 52 + ..._generated_folders_get_iam_policy_async.py | 53 + ...3_generated_folders_get_iam_policy_sync.py | 53 + ...v3_generated_folders_list_folders_async.py | 53 + ..._v3_generated_folders_list_folders_sync.py | 53 + ..._v3_generated_folders_move_folder_async.py | 57 + ...r_v3_generated_folders_move_folder_sync.py | 57 + ..._generated_folders_search_folders_async.py | 52 + ...3_generated_folders_search_folders_sync.py | 52 + ..._generated_folders_set_iam_policy_async.py | 53 + ...3_generated_folders_set_iam_policy_sync.py | 53 + ...ated_folders_test_iam_permissions_async.py | 54 + ...rated_folders_test_iam_permissions_sync.py | 54 + ...generated_folders_undelete_folder_async.py | 56 + ..._generated_folders_undelete_folder_sync.py | 56 + ...3_generated_folders_update_folder_async.py | 59 + ...v3_generated_folders_update_folder_sync.py | 59 + ...ated_organizations_get_iam_policy_async.py | 53 + ...rated_organizations_get_iam_policy_sync.py | 53 + ...ed_organizations_get_organization_async.py | 52 + ...ted_organizations_get_organization_sync.py | 52 + ...rganizations_search_organizations_async.py | 52 + ...organizations_search_organizations_sync.py | 52 + ...ated_organizations_set_iam_policy_async.py | 53 + ...rated_organizations_set_iam_policy_sync.py | 53 + ...rganizations_test_iam_permissions_async.py | 54 + ...organizations_test_iam_permissions_sync.py | 54 + ...generated_projects_create_project_async.py | 55 + ..._generated_projects_create_project_sync.py | 55 + ...generated_projects_delete_project_async.py | 56 + ..._generated_projects_delete_project_sync.py | 56 + ...generated_projects_get_iam_policy_async.py | 53 + ..._generated_projects_get_iam_policy_sync.py | 53 + ...v3_generated_projects_get_project_async.py | 52 + ..._v3_generated_projects_get_project_sync.py | 52 + ..._generated_projects_list_projects_async.py | 53 + ...3_generated_projects_list_projects_sync.py | 53 + ...3_generated_projects_move_project_async.py | 57 + ...v3_generated_projects_move_project_sync.py | 57 + ...enerated_projects_search_projects_async.py | 52 + ...generated_projects_search_projects_sync.py | 52 + ...generated_projects_set_iam_policy_async.py | 53 + ..._generated_projects_set_iam_policy_sync.py | 53 + ...ted_projects_test_iam_permissions_async.py | 54 + ...ated_projects_test_iam_permissions_sync.py | 54 + ...nerated_projects_undelete_project_async.py | 56 + ...enerated_projects_undelete_project_sync.py | 56 + ...generated_projects_update_project_async.py | 55 + ..._generated_projects_update_project_sync.py | 55 + ...d_tag_bindings_create_tag_binding_async.py | 55 + ...ed_tag_bindings_create_tag_binding_sync.py | 55 + ...d_tag_bindings_delete_tag_binding_async.py | 56 + ...ed_tag_bindings_delete_tag_binding_sync.py | 56 + ...ed_tag_bindings_list_tag_bindings_async.py | 53 + ...ted_tag_bindings_list_tag_bindings_sync.py | 53 + ...generated_tag_keys_create_tag_key_async.py | 59 + ..._generated_tag_keys_create_tag_key_sync.py | 59 + ...generated_tag_keys_delete_tag_key_async.py | 56 + ..._generated_tag_keys_delete_tag_key_sync.py | 56 + ...generated_tag_keys_get_iam_policy_async.py | 53 + ..._generated_tag_keys_get_iam_policy_sync.py | 53 + ...v3_generated_tag_keys_get_tag_key_async.py | 52 + ..._v3_generated_tag_keys_get_tag_key_sync.py | 52 + ..._generated_tag_keys_list_tag_keys_async.py | 53 + ...3_generated_tag_keys_list_tag_keys_sync.py | 53 + ...generated_tag_keys_set_iam_policy_async.py | 53 + ..._generated_tag_keys_set_iam_policy_sync.py | 53 + ...ted_tag_keys_test_iam_permissions_async.py | 54 + ...ated_tag_keys_test_iam_permissions_sync.py | 54 + ...generated_tag_keys_update_tag_key_async.py | 59 + ..._generated_tag_keys_update_tag_key_sync.py | 59 + ...rated_tag_values_create_tag_value_async.py | 59 + ...erated_tag_values_create_tag_value_sync.py | 59 + ...rated_tag_values_delete_tag_value_async.py | 56 + ...erated_tag_values_delete_tag_value_sync.py | 56 + ...nerated_tag_values_get_iam_policy_async.py | 53 + ...enerated_tag_values_get_iam_policy_sync.py | 53 + ...enerated_tag_values_get_tag_value_async.py | 52 + ...generated_tag_values_get_tag_value_sync.py | 52 + ...erated_tag_values_list_tag_values_async.py | 53 + ...nerated_tag_values_list_tag_values_sync.py | 53 + ...nerated_tag_values_set_iam_policy_async.py | 53 + ...enerated_tag_values_set_iam_policy_sync.py | 53 + ...d_tag_values_test_iam_permissions_async.py | 54 + ...ed_tag_values_test_iam_permissions_sync.py | 54 + ...rated_tag_values_update_tag_value_async.py | 59 + ...erated_tag_values_update_tag_value_sync.py | 59 + ...adata_google.cloud.resourcemanager.v3.json | 7509 +++++++++++++++++ .../fixup_resourcemanager_v3_keywords.py | 209 + owl-bot-staging/v3/setup.py | 91 + .../v3/testing/constraints-3.10.txt | 7 + .../v3/testing/constraints-3.11.txt | 7 + .../v3/testing/constraints-3.12.txt | 7 + .../v3/testing/constraints-3.7.txt | 10 + .../v3/testing/constraints-3.8.txt | 7 + .../v3/testing/constraints-3.9.txt | 7 + owl-bot-staging/v3/tests/__init__.py | 16 + owl-bot-staging/v3/tests/unit/__init__.py | 16 + .../v3/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/resourcemanager_v3/__init__.py | 16 + .../gapic/resourcemanager_v3/test_folders.py | 6753 +++++++++++++++ .../resourcemanager_v3/test_organizations.py | 3765 +++++++++ .../gapic/resourcemanager_v3/test_projects.py | 6759 +++++++++++++++ .../resourcemanager_v3/test_tag_bindings.py | 2788 ++++++ .../gapic/resourcemanager_v3/test_tag_keys.py | 5257 ++++++++++++ .../resourcemanager_v3/test_tag_values.py | 5257 ++++++++++++ 196 files changed, 80344 insertions(+) create mode 100644 owl-bot-staging/v3/.coveragerc create mode 100644 owl-bot-staging/v3/.flake8 create mode 100644 owl-bot-staging/v3/MANIFEST.in create mode 100644 owl-bot-staging/v3/README.rst create mode 100644 owl-bot-staging/v3/docs/conf.py create mode 100644 owl-bot-staging/v3/docs/index.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/services.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst create mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/types.rst create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager/py.typed create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py create mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py create mode 100644 owl-bot-staging/v3/mypy.ini create mode 100644 owl-bot-staging/v3/noxfile.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py create mode 100644 owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json create mode 100644 owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py create mode 100644 owl-bot-staging/v3/setup.py create mode 100644 owl-bot-staging/v3/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v3/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v3/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v3/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v3/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v3/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v3/tests/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py diff --git a/owl-bot-staging/v3/.coveragerc b/owl-bot-staging/v3/.coveragerc new file mode 100644 index 0000000..174fd94 --- /dev/null +++ b/owl-bot-staging/v3/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/resourcemanager/__init__.py + google/cloud/resourcemanager/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/v3/.flake8 b/owl-bot-staging/v3/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v3/.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/v3/MANIFEST.in b/owl-bot-staging/v3/MANIFEST.in new file mode 100644 index 0000000..98a88f5 --- /dev/null +++ b/owl-bot-staging/v3/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/resourcemanager *.py +recursive-include google/cloud/resourcemanager_v3 *.py diff --git a/owl-bot-staging/v3/README.rst b/owl-bot-staging/v3/README.rst new file mode 100644 index 0000000..eb02798 --- /dev/null +++ b/owl-bot-staging/v3/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Resourcemanager 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 Resourcemanager 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/v3/docs/conf.py b/owl-bot-staging/v3/docs/conf.py new file mode 100644 index 0000000..e45af88 --- /dev/null +++ b/owl-bot-staging/v3/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-resource-manager 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-resource-manager" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud 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-resource-manager-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-resource-manager.tex", + u"google-cloud-resource-manager 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-resource-manager", + u"Google Cloud Resourcemanager 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-resource-manager", + u"google-cloud-resource-manager Documentation", + author, + "google-cloud-resource-manager", + "GAPIC library for Google Cloud Resourcemanager 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/v3/docs/index.rst b/owl-bot-staging/v3/docs/index.rst new file mode 100644 index 0000000..095c171 --- /dev/null +++ b/owl-bot-staging/v3/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + resourcemanager_v3/services + resourcemanager_v3/types diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst new file mode 100644 index 0000000..3e84ddf --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst @@ -0,0 +1,10 @@ +Folders +------------------------- + +.. automodule:: google.cloud.resourcemanager_v3.services.folders + :members: + :inherited-members: + +.. automodule:: google.cloud.resourcemanager_v3.services.folders.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst new file mode 100644 index 0000000..30d36b0 --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst @@ -0,0 +1,10 @@ +Organizations +------------------------------- + +.. automodule:: google.cloud.resourcemanager_v3.services.organizations + :members: + :inherited-members: + +.. automodule:: google.cloud.resourcemanager_v3.services.organizations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst new file mode 100644 index 0000000..496baf0 --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst @@ -0,0 +1,10 @@ +Projects +-------------------------- + +.. automodule:: google.cloud.resourcemanager_v3.services.projects + :members: + :inherited-members: + +.. automodule:: google.cloud.resourcemanager_v3.services.projects.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/services.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/services.rst new file mode 100644 index 0000000..c542a30 --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/services.rst @@ -0,0 +1,11 @@ +Services for Google Cloud Resourcemanager v3 API +================================================ +.. toctree:: + :maxdepth: 2 + + folders + organizations + projects + tag_bindings + tag_keys + tag_values diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst new file mode 100644 index 0000000..313ea3d --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst @@ -0,0 +1,10 @@ +TagBindings +----------------------------- + +.. automodule:: google.cloud.resourcemanager_v3.services.tag_bindings + :members: + :inherited-members: + +.. automodule:: google.cloud.resourcemanager_v3.services.tag_bindings.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst new file mode 100644 index 0000000..f8d408f --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst @@ -0,0 +1,10 @@ +TagKeys +------------------------- + +.. automodule:: google.cloud.resourcemanager_v3.services.tag_keys + :members: + :inherited-members: + +.. automodule:: google.cloud.resourcemanager_v3.services.tag_keys.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst new file mode 100644 index 0000000..f4fa247 --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst @@ -0,0 +1,10 @@ +TagValues +--------------------------- + +.. automodule:: google.cloud.resourcemanager_v3.services.tag_values + :members: + :inherited-members: + +.. automodule:: google.cloud.resourcemanager_v3.services.tag_values.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/types.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/types.rst new file mode 100644 index 0000000..c265f6e --- /dev/null +++ b/owl-bot-staging/v3/docs/resourcemanager_v3/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Resourcemanager v3 API +============================================= + +.. automodule:: google.cloud.resourcemanager_v3.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py new file mode 100644 index 0000000..0a90129 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.resourcemanager_v3.services.folders.client import FoldersClient +from google.cloud.resourcemanager_v3.services.folders.async_client import FoldersAsyncClient +from google.cloud.resourcemanager_v3.services.organizations.client import OrganizationsClient +from google.cloud.resourcemanager_v3.services.organizations.async_client import OrganizationsAsyncClient +from google.cloud.resourcemanager_v3.services.projects.client import ProjectsClient +from google.cloud.resourcemanager_v3.services.projects.async_client import ProjectsAsyncClient +from google.cloud.resourcemanager_v3.services.tag_bindings.client import TagBindingsClient +from google.cloud.resourcemanager_v3.services.tag_bindings.async_client import TagBindingsAsyncClient +from google.cloud.resourcemanager_v3.services.tag_keys.client import TagKeysClient +from google.cloud.resourcemanager_v3.services.tag_keys.async_client import TagKeysAsyncClient +from google.cloud.resourcemanager_v3.services.tag_values.client import TagValuesClient +from google.cloud.resourcemanager_v3.services.tag_values.async_client import TagValuesAsyncClient + +from google.cloud.resourcemanager_v3.types.folders import CreateFolderMetadata +from google.cloud.resourcemanager_v3.types.folders import CreateFolderRequest +from google.cloud.resourcemanager_v3.types.folders import DeleteFolderMetadata +from google.cloud.resourcemanager_v3.types.folders import DeleteFolderRequest +from google.cloud.resourcemanager_v3.types.folders import Folder +from google.cloud.resourcemanager_v3.types.folders import GetFolderRequest +from google.cloud.resourcemanager_v3.types.folders import ListFoldersRequest +from google.cloud.resourcemanager_v3.types.folders import ListFoldersResponse +from google.cloud.resourcemanager_v3.types.folders import MoveFolderMetadata +from google.cloud.resourcemanager_v3.types.folders import MoveFolderRequest +from google.cloud.resourcemanager_v3.types.folders import SearchFoldersRequest +from google.cloud.resourcemanager_v3.types.folders import SearchFoldersResponse +from google.cloud.resourcemanager_v3.types.folders import UndeleteFolderMetadata +from google.cloud.resourcemanager_v3.types.folders import UndeleteFolderRequest +from google.cloud.resourcemanager_v3.types.folders import UpdateFolderMetadata +from google.cloud.resourcemanager_v3.types.folders import UpdateFolderRequest +from google.cloud.resourcemanager_v3.types.organizations import DeleteOrganizationMetadata +from google.cloud.resourcemanager_v3.types.organizations import GetOrganizationRequest +from google.cloud.resourcemanager_v3.types.organizations import Organization +from google.cloud.resourcemanager_v3.types.organizations import SearchOrganizationsRequest +from google.cloud.resourcemanager_v3.types.organizations import SearchOrganizationsResponse +from google.cloud.resourcemanager_v3.types.organizations import UndeleteOrganizationMetadata +from google.cloud.resourcemanager_v3.types.projects import CreateProjectMetadata +from google.cloud.resourcemanager_v3.types.projects import CreateProjectRequest +from google.cloud.resourcemanager_v3.types.projects import DeleteProjectMetadata +from google.cloud.resourcemanager_v3.types.projects import DeleteProjectRequest +from google.cloud.resourcemanager_v3.types.projects import GetProjectRequest +from google.cloud.resourcemanager_v3.types.projects import ListProjectsRequest +from google.cloud.resourcemanager_v3.types.projects import ListProjectsResponse +from google.cloud.resourcemanager_v3.types.projects import MoveProjectMetadata +from google.cloud.resourcemanager_v3.types.projects import MoveProjectRequest +from google.cloud.resourcemanager_v3.types.projects import Project +from google.cloud.resourcemanager_v3.types.projects import SearchProjectsRequest +from google.cloud.resourcemanager_v3.types.projects import SearchProjectsResponse +from google.cloud.resourcemanager_v3.types.projects import UndeleteProjectMetadata +from google.cloud.resourcemanager_v3.types.projects import UndeleteProjectRequest +from google.cloud.resourcemanager_v3.types.projects import UpdateProjectMetadata +from google.cloud.resourcemanager_v3.types.projects import UpdateProjectRequest +from google.cloud.resourcemanager_v3.types.tag_bindings import CreateTagBindingMetadata +from google.cloud.resourcemanager_v3.types.tag_bindings import CreateTagBindingRequest +from google.cloud.resourcemanager_v3.types.tag_bindings import DeleteTagBindingMetadata +from google.cloud.resourcemanager_v3.types.tag_bindings import DeleteTagBindingRequest +from google.cloud.resourcemanager_v3.types.tag_bindings import ListTagBindingsRequest +from google.cloud.resourcemanager_v3.types.tag_bindings import ListTagBindingsResponse +from google.cloud.resourcemanager_v3.types.tag_bindings import TagBinding +from google.cloud.resourcemanager_v3.types.tag_keys import CreateTagKeyMetadata +from google.cloud.resourcemanager_v3.types.tag_keys import CreateTagKeyRequest +from google.cloud.resourcemanager_v3.types.tag_keys import DeleteTagKeyMetadata +from google.cloud.resourcemanager_v3.types.tag_keys import DeleteTagKeyRequest +from google.cloud.resourcemanager_v3.types.tag_keys import GetTagKeyRequest +from google.cloud.resourcemanager_v3.types.tag_keys import ListTagKeysRequest +from google.cloud.resourcemanager_v3.types.tag_keys import ListTagKeysResponse +from google.cloud.resourcemanager_v3.types.tag_keys import TagKey +from google.cloud.resourcemanager_v3.types.tag_keys import UpdateTagKeyMetadata +from google.cloud.resourcemanager_v3.types.tag_keys import UpdateTagKeyRequest +from google.cloud.resourcemanager_v3.types.tag_values import CreateTagValueMetadata +from google.cloud.resourcemanager_v3.types.tag_values import CreateTagValueRequest +from google.cloud.resourcemanager_v3.types.tag_values import DeleteTagValueMetadata +from google.cloud.resourcemanager_v3.types.tag_values import DeleteTagValueRequest +from google.cloud.resourcemanager_v3.types.tag_values import GetTagValueRequest +from google.cloud.resourcemanager_v3.types.tag_values import ListTagValuesRequest +from google.cloud.resourcemanager_v3.types.tag_values import ListTagValuesResponse +from google.cloud.resourcemanager_v3.types.tag_values import TagValue +from google.cloud.resourcemanager_v3.types.tag_values import UpdateTagValueMetadata +from google.cloud.resourcemanager_v3.types.tag_values import UpdateTagValueRequest + +__all__ = ('FoldersClient', + 'FoldersAsyncClient', + 'OrganizationsClient', + 'OrganizationsAsyncClient', + 'ProjectsClient', + 'ProjectsAsyncClient', + 'TagBindingsClient', + 'TagBindingsAsyncClient', + 'TagKeysClient', + 'TagKeysAsyncClient', + 'TagValuesClient', + 'TagValuesAsyncClient', + 'CreateFolderMetadata', + 'CreateFolderRequest', + 'DeleteFolderMetadata', + 'DeleteFolderRequest', + 'Folder', + 'GetFolderRequest', + 'ListFoldersRequest', + 'ListFoldersResponse', + 'MoveFolderMetadata', + 'MoveFolderRequest', + 'SearchFoldersRequest', + 'SearchFoldersResponse', + 'UndeleteFolderMetadata', + 'UndeleteFolderRequest', + 'UpdateFolderMetadata', + 'UpdateFolderRequest', + 'DeleteOrganizationMetadata', + 'GetOrganizationRequest', + 'Organization', + 'SearchOrganizationsRequest', + 'SearchOrganizationsResponse', + 'UndeleteOrganizationMetadata', + 'CreateProjectMetadata', + 'CreateProjectRequest', + 'DeleteProjectMetadata', + 'DeleteProjectRequest', + 'GetProjectRequest', + 'ListProjectsRequest', + 'ListProjectsResponse', + 'MoveProjectMetadata', + 'MoveProjectRequest', + 'Project', + 'SearchProjectsRequest', + 'SearchProjectsResponse', + 'UndeleteProjectMetadata', + 'UndeleteProjectRequest', + 'UpdateProjectMetadata', + 'UpdateProjectRequest', + 'CreateTagBindingMetadata', + 'CreateTagBindingRequest', + 'DeleteTagBindingMetadata', + 'DeleteTagBindingRequest', + 'ListTagBindingsRequest', + 'ListTagBindingsResponse', + 'TagBinding', + 'CreateTagKeyMetadata', + 'CreateTagKeyRequest', + 'DeleteTagKeyMetadata', + 'DeleteTagKeyRequest', + 'GetTagKeyRequest', + 'ListTagKeysRequest', + 'ListTagKeysResponse', + 'TagKey', + 'UpdateTagKeyMetadata', + 'UpdateTagKeyRequest', + 'CreateTagValueMetadata', + 'CreateTagValueRequest', + 'DeleteTagValueMetadata', + 'DeleteTagValueRequest', + 'GetTagValueRequest', + 'ListTagValuesRequest', + 'ListTagValuesResponse', + 'TagValue', + 'UpdateTagValueMetadata', + 'UpdateTagValueRequest', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py b/owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager/py.typed b/owl-bot-staging/v3/google/cloud/resourcemanager/py.typed new file mode 100644 index 0000000..b1e13d7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-resource-manager package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py new file mode 100644 index 0000000..16ccc26 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.folders import FoldersClient +from .services.folders import FoldersAsyncClient +from .services.organizations import OrganizationsClient +from .services.organizations import OrganizationsAsyncClient +from .services.projects import ProjectsClient +from .services.projects import ProjectsAsyncClient +from .services.tag_bindings import TagBindingsClient +from .services.tag_bindings import TagBindingsAsyncClient +from .services.tag_keys import TagKeysClient +from .services.tag_keys import TagKeysAsyncClient +from .services.tag_values import TagValuesClient +from .services.tag_values import TagValuesAsyncClient + +from .types.folders import CreateFolderMetadata +from .types.folders import CreateFolderRequest +from .types.folders import DeleteFolderMetadata +from .types.folders import DeleteFolderRequest +from .types.folders import Folder +from .types.folders import GetFolderRequest +from .types.folders import ListFoldersRequest +from .types.folders import ListFoldersResponse +from .types.folders import MoveFolderMetadata +from .types.folders import MoveFolderRequest +from .types.folders import SearchFoldersRequest +from .types.folders import SearchFoldersResponse +from .types.folders import UndeleteFolderMetadata +from .types.folders import UndeleteFolderRequest +from .types.folders import UpdateFolderMetadata +from .types.folders import UpdateFolderRequest +from .types.organizations import DeleteOrganizationMetadata +from .types.organizations import GetOrganizationRequest +from .types.organizations import Organization +from .types.organizations import SearchOrganizationsRequest +from .types.organizations import SearchOrganizationsResponse +from .types.organizations import UndeleteOrganizationMetadata +from .types.projects import CreateProjectMetadata +from .types.projects import CreateProjectRequest +from .types.projects import DeleteProjectMetadata +from .types.projects import DeleteProjectRequest +from .types.projects import GetProjectRequest +from .types.projects import ListProjectsRequest +from .types.projects import ListProjectsResponse +from .types.projects import MoveProjectMetadata +from .types.projects import MoveProjectRequest +from .types.projects import Project +from .types.projects import SearchProjectsRequest +from .types.projects import SearchProjectsResponse +from .types.projects import UndeleteProjectMetadata +from .types.projects import UndeleteProjectRequest +from .types.projects import UpdateProjectMetadata +from .types.projects import UpdateProjectRequest +from .types.tag_bindings import CreateTagBindingMetadata +from .types.tag_bindings import CreateTagBindingRequest +from .types.tag_bindings import DeleteTagBindingMetadata +from .types.tag_bindings import DeleteTagBindingRequest +from .types.tag_bindings import ListTagBindingsRequest +from .types.tag_bindings import ListTagBindingsResponse +from .types.tag_bindings import TagBinding +from .types.tag_keys import CreateTagKeyMetadata +from .types.tag_keys import CreateTagKeyRequest +from .types.tag_keys import DeleteTagKeyMetadata +from .types.tag_keys import DeleteTagKeyRequest +from .types.tag_keys import GetTagKeyRequest +from .types.tag_keys import ListTagKeysRequest +from .types.tag_keys import ListTagKeysResponse +from .types.tag_keys import TagKey +from .types.tag_keys import UpdateTagKeyMetadata +from .types.tag_keys import UpdateTagKeyRequest +from .types.tag_values import CreateTagValueMetadata +from .types.tag_values import CreateTagValueRequest +from .types.tag_values import DeleteTagValueMetadata +from .types.tag_values import DeleteTagValueRequest +from .types.tag_values import GetTagValueRequest +from .types.tag_values import ListTagValuesRequest +from .types.tag_values import ListTagValuesResponse +from .types.tag_values import TagValue +from .types.tag_values import UpdateTagValueMetadata +from .types.tag_values import UpdateTagValueRequest + +__all__ = ( + 'FoldersAsyncClient', + 'OrganizationsAsyncClient', + 'ProjectsAsyncClient', + 'TagBindingsAsyncClient', + 'TagKeysAsyncClient', + 'TagValuesAsyncClient', +'CreateFolderMetadata', +'CreateFolderRequest', +'CreateProjectMetadata', +'CreateProjectRequest', +'CreateTagBindingMetadata', +'CreateTagBindingRequest', +'CreateTagKeyMetadata', +'CreateTagKeyRequest', +'CreateTagValueMetadata', +'CreateTagValueRequest', +'DeleteFolderMetadata', +'DeleteFolderRequest', +'DeleteOrganizationMetadata', +'DeleteProjectMetadata', +'DeleteProjectRequest', +'DeleteTagBindingMetadata', +'DeleteTagBindingRequest', +'DeleteTagKeyMetadata', +'DeleteTagKeyRequest', +'DeleteTagValueMetadata', +'DeleteTagValueRequest', +'Folder', +'FoldersClient', +'GetFolderRequest', +'GetOrganizationRequest', +'GetProjectRequest', +'GetTagKeyRequest', +'GetTagValueRequest', +'ListFoldersRequest', +'ListFoldersResponse', +'ListProjectsRequest', +'ListProjectsResponse', +'ListTagBindingsRequest', +'ListTagBindingsResponse', +'ListTagKeysRequest', +'ListTagKeysResponse', +'ListTagValuesRequest', +'ListTagValuesResponse', +'MoveFolderMetadata', +'MoveFolderRequest', +'MoveProjectMetadata', +'MoveProjectRequest', +'Organization', +'OrganizationsClient', +'Project', +'ProjectsClient', +'SearchFoldersRequest', +'SearchFoldersResponse', +'SearchOrganizationsRequest', +'SearchOrganizationsResponse', +'SearchProjectsRequest', +'SearchProjectsResponse', +'TagBinding', +'TagBindingsClient', +'TagKey', +'TagKeysClient', +'TagValue', +'TagValuesClient', +'UndeleteFolderMetadata', +'UndeleteFolderRequest', +'UndeleteOrganizationMetadata', +'UndeleteProjectMetadata', +'UndeleteProjectRequest', +'UpdateFolderMetadata', +'UpdateFolderRequest', +'UpdateProjectMetadata', +'UpdateProjectRequest', +'UpdateTagKeyMetadata', +'UpdateTagKeyRequest', +'UpdateTagValueMetadata', +'UpdateTagValueRequest', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json new file mode 100644 index 0000000..b1415c1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json @@ -0,0 +1,813 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.resourcemanager_v3", + "protoPackage": "google.cloud.resourcemanager.v3", + "schema": "1.0", + "services": { + "Folders": { + "clients": { + "grpc": { + "libraryClient": "FoldersClient", + "rpcs": { + "CreateFolder": { + "methods": [ + "create_folder" + ] + }, + "DeleteFolder": { + "methods": [ + "delete_folder" + ] + }, + "GetFolder": { + "methods": [ + "get_folder" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFolders": { + "methods": [ + "list_folders" + ] + }, + "MoveFolder": { + "methods": [ + "move_folder" + ] + }, + "SearchFolders": { + "methods": [ + "search_folders" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteFolder": { + "methods": [ + "undelete_folder" + ] + }, + "UpdateFolder": { + "methods": [ + "update_folder" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FoldersAsyncClient", + "rpcs": { + "CreateFolder": { + "methods": [ + "create_folder" + ] + }, + "DeleteFolder": { + "methods": [ + "delete_folder" + ] + }, + "GetFolder": { + "methods": [ + "get_folder" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFolders": { + "methods": [ + "list_folders" + ] + }, + "MoveFolder": { + "methods": [ + "move_folder" + ] + }, + "SearchFolders": { + "methods": [ + "search_folders" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteFolder": { + "methods": [ + "undelete_folder" + ] + }, + "UpdateFolder": { + "methods": [ + "update_folder" + ] + } + } + }, + "rest": { + "libraryClient": "FoldersClient", + "rpcs": { + "CreateFolder": { + "methods": [ + "create_folder" + ] + }, + "DeleteFolder": { + "methods": [ + "delete_folder" + ] + }, + "GetFolder": { + "methods": [ + "get_folder" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListFolders": { + "methods": [ + "list_folders" + ] + }, + "MoveFolder": { + "methods": [ + "move_folder" + ] + }, + "SearchFolders": { + "methods": [ + "search_folders" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteFolder": { + "methods": [ + "undelete_folder" + ] + }, + "UpdateFolder": { + "methods": [ + "update_folder" + ] + } + } + } + } + }, + "Organizations": { + "clients": { + "grpc": { + "libraryClient": "OrganizationsClient", + "rpcs": { + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganization": { + "methods": [ + "get_organization" + ] + }, + "SearchOrganizations": { + "methods": [ + "search_organizations" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OrganizationsAsyncClient", + "rpcs": { + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganization": { + "methods": [ + "get_organization" + ] + }, + "SearchOrganizations": { + "methods": [ + "search_organizations" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + }, + "rest": { + "libraryClient": "OrganizationsClient", + "rpcs": { + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganization": { + "methods": [ + "get_organization" + ] + }, + "SearchOrganizations": { + "methods": [ + "search_organizations" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, + "Projects": { + "clients": { + "grpc": { + "libraryClient": "ProjectsClient", + "rpcs": { + "CreateProject": { + "methods": [ + "create_project" + ] + }, + "DeleteProject": { + "methods": [ + "delete_project" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetProject": { + "methods": [ + "get_project" + ] + }, + "ListProjects": { + "methods": [ + "list_projects" + ] + }, + "MoveProject": { + "methods": [ + "move_project" + ] + }, + "SearchProjects": { + "methods": [ + "search_projects" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteProject": { + "methods": [ + "undelete_project" + ] + }, + "UpdateProject": { + "methods": [ + "update_project" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProjectsAsyncClient", + "rpcs": { + "CreateProject": { + "methods": [ + "create_project" + ] + }, + "DeleteProject": { + "methods": [ + "delete_project" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetProject": { + "methods": [ + "get_project" + ] + }, + "ListProjects": { + "methods": [ + "list_projects" + ] + }, + "MoveProject": { + "methods": [ + "move_project" + ] + }, + "SearchProjects": { + "methods": [ + "search_projects" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteProject": { + "methods": [ + "undelete_project" + ] + }, + "UpdateProject": { + "methods": [ + "update_project" + ] + } + } + }, + "rest": { + "libraryClient": "ProjectsClient", + "rpcs": { + "CreateProject": { + "methods": [ + "create_project" + ] + }, + "DeleteProject": { + "methods": [ + "delete_project" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetProject": { + "methods": [ + "get_project" + ] + }, + "ListProjects": { + "methods": [ + "list_projects" + ] + }, + "MoveProject": { + "methods": [ + "move_project" + ] + }, + "SearchProjects": { + "methods": [ + "search_projects" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteProject": { + "methods": [ + "undelete_project" + ] + }, + "UpdateProject": { + "methods": [ + "update_project" + ] + } + } + } + } + }, + "TagBindings": { + "clients": { + "grpc": { + "libraryClient": "TagBindingsClient", + "rpcs": { + "CreateTagBinding": { + "methods": [ + "create_tag_binding" + ] + }, + "DeleteTagBinding": { + "methods": [ + "delete_tag_binding" + ] + }, + "ListTagBindings": { + "methods": [ + "list_tag_bindings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TagBindingsAsyncClient", + "rpcs": { + "CreateTagBinding": { + "methods": [ + "create_tag_binding" + ] + }, + "DeleteTagBinding": { + "methods": [ + "delete_tag_binding" + ] + }, + "ListTagBindings": { + "methods": [ + "list_tag_bindings" + ] + } + } + }, + "rest": { + "libraryClient": "TagBindingsClient", + "rpcs": { + "CreateTagBinding": { + "methods": [ + "create_tag_binding" + ] + }, + "DeleteTagBinding": { + "methods": [ + "delete_tag_binding" + ] + }, + "ListTagBindings": { + "methods": [ + "list_tag_bindings" + ] + } + } + } + } + }, + "TagKeys": { + "clients": { + "grpc": { + "libraryClient": "TagKeysClient", + "rpcs": { + "CreateTagKey": { + "methods": [ + "create_tag_key" + ] + }, + "DeleteTagKey": { + "methods": [ + "delete_tag_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagKey": { + "methods": [ + "get_tag_key" + ] + }, + "ListTagKeys": { + "methods": [ + "list_tag_keys" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateTagKey": { + "methods": [ + "update_tag_key" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TagKeysAsyncClient", + "rpcs": { + "CreateTagKey": { + "methods": [ + "create_tag_key" + ] + }, + "DeleteTagKey": { + "methods": [ + "delete_tag_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagKey": { + "methods": [ + "get_tag_key" + ] + }, + "ListTagKeys": { + "methods": [ + "list_tag_keys" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateTagKey": { + "methods": [ + "update_tag_key" + ] + } + } + }, + "rest": { + "libraryClient": "TagKeysClient", + "rpcs": { + "CreateTagKey": { + "methods": [ + "create_tag_key" + ] + }, + "DeleteTagKey": { + "methods": [ + "delete_tag_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagKey": { + "methods": [ + "get_tag_key" + ] + }, + "ListTagKeys": { + "methods": [ + "list_tag_keys" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateTagKey": { + "methods": [ + "update_tag_key" + ] + } + } + } + } + }, + "TagValues": { + "clients": { + "grpc": { + "libraryClient": "TagValuesClient", + "rpcs": { + "CreateTagValue": { + "methods": [ + "create_tag_value" + ] + }, + "DeleteTagValue": { + "methods": [ + "delete_tag_value" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagValue": { + "methods": [ + "get_tag_value" + ] + }, + "ListTagValues": { + "methods": [ + "list_tag_values" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateTagValue": { + "methods": [ + "update_tag_value" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TagValuesAsyncClient", + "rpcs": { + "CreateTagValue": { + "methods": [ + "create_tag_value" + ] + }, + "DeleteTagValue": { + "methods": [ + "delete_tag_value" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagValue": { + "methods": [ + "get_tag_value" + ] + }, + "ListTagValues": { + "methods": [ + "list_tag_values" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateTagValue": { + "methods": [ + "update_tag_value" + ] + } + } + }, + "rest": { + "libraryClient": "TagValuesClient", + "rpcs": { + "CreateTagValue": { + "methods": [ + "create_tag_value" + ] + }, + "DeleteTagValue": { + "methods": [ + "delete_tag_value" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetTagValue": { + "methods": [ + "get_tag_value" + ] + }, + "ListTagValues": { + "methods": [ + "list_tag_values" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateTagValue": { + "methods": [ + "update_tag_value" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed new file mode 100644 index 0000000..b1e13d7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-resource-manager package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py new file mode 100644 index 0000000..eeb7430 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FoldersClient +from .async_client import FoldersAsyncClient + +__all__ = ( + 'FoldersClient', + 'FoldersAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py new file mode 100644 index 0000000..f9886b3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py @@ -0,0 +1,1724 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.folders import pagers +from google.cloud.resourcemanager_v3.types import folders +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FoldersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FoldersGrpcAsyncIOTransport +from .client import FoldersClient + + +class FoldersAsyncClient: + """Manages Cloud Platform folder resources. + Folders can be used to organize the resources under an + organization and to control the policies applied to groups of + resources. + """ + + _client: FoldersClient + + DEFAULT_ENDPOINT = FoldersClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FoldersClient.DEFAULT_MTLS_ENDPOINT + + folder_path = staticmethod(FoldersClient.folder_path) + parse_folder_path = staticmethod(FoldersClient.parse_folder_path) + common_billing_account_path = staticmethod(FoldersClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FoldersClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FoldersClient.common_folder_path) + parse_common_folder_path = staticmethod(FoldersClient.parse_common_folder_path) + common_organization_path = staticmethod(FoldersClient.common_organization_path) + parse_common_organization_path = staticmethod(FoldersClient.parse_common_organization_path) + common_project_path = staticmethod(FoldersClient.common_project_path) + parse_common_project_path = staticmethod(FoldersClient.parse_common_project_path) + common_location_path = staticmethod(FoldersClient.common_location_path) + parse_common_location_path = staticmethod(FoldersClient.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: + FoldersAsyncClient: The constructed client. + """ + return FoldersClient.from_service_account_info.__func__(FoldersAsyncClient, 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: + FoldersAsyncClient: The constructed client. + """ + return FoldersClient.from_service_account_file.__func__(FoldersAsyncClient, 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 FoldersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> FoldersTransport: + """Returns the transport used by the client instance. + + Returns: + FoldersTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FoldersClient).get_transport_class, type(FoldersClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FoldersTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the folders client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.FoldersTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = FoldersClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_folder(self, + request: Optional[Union[folders.GetFolderRequest, 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]] = (), + ) -> folders.Folder: + r"""Retrieves a folder identified by the supplied resource name. + Valid folder resource names have the format + ``folders/{folder_id}`` (for example, ``folders/1234``). The + caller must have ``resourcemanager.folders.get`` permission on + the identified 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 resourcemanager_v3 + + async def sample_get_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetFolderRequest( + name="name_value", + ) + + # Make the request + response = await client.get_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.GetFolderRequest, dict]]): + The request object. The GetFolder request message. + name (:class:`str`): + Required. The resource name of the folder to retrieve. + Must be of the form ``folders/{folder_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.resourcemanager_v3.types.Folder: + A folder in an organization's + resource hierarchy, used to organize + that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.GetFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_folder, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_folders(self, + request: Optional[Union[folders.ListFoldersRequest, 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.ListFoldersAsyncPager: + r"""Lists the folders that are direct descendants of supplied parent + resource. ``list()`` provides a strongly consistent view of the + folders underneath the specified parent resource. ``list()`` + returns folders sorted based upon the (ascending) lexical + ordering of their display_name. The caller must have + ``resourcemanager.folders.list`` permission on the identified + parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_list_folders(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_folders(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.ListFoldersRequest, dict]]): + The request object. The ListFolders request message. + parent (:class:`str`): + Required. The resource name of the organization or + folder whose folders are being listed. Must be of the + form ``folders/{folder_id}`` or + ``organizations/{org_id}``. Access to this method is + controlled by checking the + ``resourcemanager.folders.list`` permission on the + ``parent``. + + 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.resourcemanager_v3.services.folders.pagers.ListFoldersAsyncPager: + The ListFolders response message. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.ListFoldersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_folders, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListFoldersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_folders(self, + request: Optional[Union[folders.SearchFoldersRequest, dict]] = None, + *, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchFoldersAsyncPager: + r"""Search for folders that match specific filter criteria. + ``search()`` provides an eventually consistent view of the + folders a user has access to which meet the specified filter + criteria. + + This will only return folders on which the caller has the + permission ``resourcemanager.folders.get``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_search_folders(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchFoldersRequest( + ) + + # Make the request + page_result = client.search_folders(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchFoldersRequest, dict]]): + The request object. The request message for searching + folders. + query (:class:`str`): + Optional. Search criteria used to select the folders to + return. If no search criteria is specified then all + accessible folders will be returned. + + Query expressions can be used to restrict results based + upon displayName, state and parent, where the operators + ``=`` (``:``) ``NOT``, ``AND`` and ``OR`` can be used + along with the suffix wildcard symbol ``*``. + + The ``displayName`` field in a query expression should + use escaped quotes for values that include whitespace to + prevent unexpected behavior. + + :: + + | Field | Description | + |-------------------------|----------------------------------------| + | displayName | Filters by displayName. | + | parent | Filters by parent (for example: folders/123). | + | state, lifecycleState | Filters by state. | + + Some example queries are: + + - Query ``displayName=Test*`` returns Folder resources + whose display name starts with "Test". + - Query ``state=ACTIVE`` returns Folder resources with + ``state`` set to ``ACTIVE``. + - Query ``parent=folders/123`` returns Folder resources + that have ``folders/123`` as a parent resource. + - Query ``parent=folders/123 AND state=ACTIVE`` returns + active Folder resources that have ``folders/123`` as + a parent resource. + - Query ``displayName=\\"Test String\\"`` returns + Folder resources with display names that include both + "Test" and "String". + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersAsyncPager: + The response message for searching + folders. + 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([query]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.SearchFoldersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_folders, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.SearchFoldersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_folder(self, + request: Optional[Union[folders.CreateFolderRequest, dict]] = None, + *, + folder: Optional[folders.Folder] = 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 folder in the resource hierarchy. Returns an + ``Operation`` which can be used to track the progress of the + folder creation workflow. Upon success, the + ``Operation.response`` field will be populated with the created + Folder. + + In order to succeed, the addition of this new folder must not + violate the folder naming, height, or fanout constraints. + + - The folder's ``display_name`` must be distinct from all other + folders that share its parent. + - The addition of the folder must not cause the active folder + hierarchy to exceed a height of 10. Note, the full active + + deleted folder hierarchy is allowed to reach a height of 20; + this provides additional headroom when moving folders that + contain deleted folders. + - The addition of the folder must not cause the total number of + folders under its parent to exceed 300. + + If the operation fails due to a folder constraint violation, + some errors may be returned by the ``CreateFolder`` request, + with status code ``FAILED_PRECONDITION`` and an error + description. Other folder constraint violations will be + communicated in the ``Operation``, with the specific + ``PreconditionFailure`` returned in the details list in the + ``Operation.error`` field. + + The caller must have ``resourcemanager.folders.create`` + permission on the identified parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_create_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.CreateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.create_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateFolderRequest, dict]]): + The request object. The CreateFolder request message. + folder (:class:`google.cloud.resourcemanager_v3.types.Folder`): + Required. The folder being created, + only the display name and parent will be + consulted. All other fields will be + ignored. + + This corresponds to the ``folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([folder]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.CreateFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if folder is not None: + request.folder = folder + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_folder, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + folders.Folder, + metadata_type=folders.CreateFolderMetadata, + ) + + # Done; return the response. + return response + + async def update_folder(self, + request: Optional[Union[folders.UpdateFolderRequest, dict]] = None, + *, + folder: Optional[folders.Folder] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a folder, changing its ``display_name``. Changes to the + folder ``display_name`` will be rejected if they violate either + the ``display_name`` formatting rules or the naming constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. + + The folder's ``display_name`` must start and end with a letter + or digit, may contain letters, digits, spaces, hyphens and + underscores and can be between 3 and 30 characters. This is + captured by the regular expression: + ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller + must have ``resourcemanager.folders.update`` permission on the + identified folder. + + If the update fails due to the unique name constraint then a + ``PreconditionFailure`` explaining this violation will be + returned in the Status.details field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_update_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.UpdateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.update_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateFolderRequest, dict]]): + The request object. The request sent to the + [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] + method. + + Only the ``display_name`` field can be changed. All + other fields will be ignored. Use the + [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] + method to change the ``parent`` field. + folder (:class:`google.cloud.resourcemanager_v3.types.Folder`): + Required. The new definition of the Folder. It must + include the ``name`` field, which cannot be changed. + + This corresponds to the ``folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Fields to be updated. Only the + ``display_name`` can be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([folder, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.UpdateFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if folder is not None: + request.folder = folder + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_folder, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("folder.name", request.folder.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + folders.Folder, + metadata_type=folders.UpdateFolderMetadata, + ) + + # Done; return the response. + return response + + async def move_folder(self, + request: Optional[Union[folders.MoveFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + destination_parent: 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"""Moves a folder under a new resource parent. Returns an + ``Operation`` which can be used to track the progress of the + folder move workflow. Upon success, the ``Operation.response`` + field will be populated with the moved folder. Upon failure, a + ``FolderOperationError`` categorizing the failure cause will be + returned - if the failure occurs synchronously then the + ``FolderOperationError`` will be returned in the + ``Status.details`` field. If it occurs asynchronously, then the + FolderOperation will be returned in the ``Operation.error`` + field. In addition, the ``Operation.metadata`` field will be + populated with a ``FolderOperation`` message as an aid to + stateless clients. Folder moves will be rejected if they violate + either the naming, height, or fanout constraints described in + the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.move`` permission on the folder's + current and proposed new parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_move_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveFolderRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.MoveFolderRequest, dict]]): + The request object. The MoveFolder request message. + name (:class:`str`): + Required. The resource name of the Folder to move. Must + be of the form folders/{folder_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + destination_parent (:class:`str`): + Required. The resource name of the folder or + organization which should be the folder's new parent. + Must be of the form ``folders/{folder_id}`` or + ``organizations/{org_id}``. + + This corresponds to the ``destination_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick 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, destination_parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.MoveFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if destination_parent is not None: + request.destination_parent = destination_parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.move_folder, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + folders.Folder, + metadata_type=folders.MoveFolderMetadata, + ) + + # Done; return the response. + return response + + async def delete_folder(self, + request: Optional[Union[folders.DeleteFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Requests deletion of a folder. The folder is moved into the + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state immediately, and is deleted approximately 30 days later. + This method may only be called on an empty folder, where a + folder is empty if it doesn't contain any folders or projects in + the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. If called on a folder in + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state the operation will result in a no-op success. The caller + must have ``resourcemanager.folders.delete`` permission on the + identified 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 resourcemanager_v3 + + async def sample_delete_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteFolderRequest, dict]]): + The request object. The DeleteFolder request message. + name (:class:`str`): + Required. The resource name of the folder to be deleted. + Must be of the form ``folders/{folder_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.DeleteFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_folder, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + folders.Folder, + metadata_type=folders.DeleteFolderMetadata, + ) + + # Done; return the response. + return response + + async def undelete_folder(self, + request: Optional[Union[folders.UndeleteFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Cancels the deletion request for a folder. This method may be + called on a folder in any state. If the folder is in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state the result will be a no-op success. In order to succeed, + the folder's parent must be in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. In addition, reintroducing the folder into the tree must + not violate folder naming, height, and fanout constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.undelete`` permission on the + identified 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 resourcemanager_v3 + + async def sample_undelete_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.UndeleteFolderRequest, dict]]): + The request object. The UndeleteFolder request message. + name (:class:`str`): + Required. The resource name of the folder to undelete. + Must be of the form ``folders/{folder_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = folders.UndeleteFolderRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.undelete_folder, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + folders.Folder, + metadata_type=folders.UndeleteFolderMetadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for a folder. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the folder's resource name, for + example: "folders/1234". The caller must have + ``resourcemanager.folders.getIamPolicy`` permission on the + identified 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 resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on a folder, replacing any + existing policy. The ``resource`` field should be the folder's + resource name, for example: "folders/1234". The caller must have + ``resourcemanager.folders.setIamPolicy`` permission on the + identified 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 resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified folder. + The ``resource`` field should be the folder's resource name, for + example: "folders/1234". + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._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), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "FoldersAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py new file mode 100644 index 0000000..e566613 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py @@ -0,0 +1,1909 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.folders import pagers +from google.cloud.resourcemanager_v3.types import folders +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FoldersTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FoldersGrpcTransport +from .transports.grpc_asyncio import FoldersGrpcAsyncIOTransport +from .transports.rest import FoldersRestTransport + + +class FoldersClientMeta(type): + """Metaclass for the Folders 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[FoldersTransport]] + _transport_registry["grpc"] = FoldersGrpcTransport + _transport_registry["grpc_asyncio"] = FoldersGrpcAsyncIOTransport + _transport_registry["rest"] = FoldersRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[FoldersTransport]: + """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 FoldersClient(metaclass=FoldersClientMeta): + """Manages Cloud Platform folder resources. + Folders can be used to organize the resources under an + organization and to control the policies applied to groups of + resources. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FoldersClient: 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: + FoldersClient: 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) -> FoldersTransport: + """Returns the transport used by the client instance. + + Returns: + FoldersTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def folder_path(folder: str,) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_folder_path(path: str) -> Dict[str,str]: + """Parses a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, FoldersTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the folders client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FoldersTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FoldersTransport): + # transport is a FoldersTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_folder(self, + request: Optional[Union[folders.GetFolderRequest, 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]] = (), + ) -> folders.Folder: + r"""Retrieves a folder identified by the supplied resource name. + Valid folder resource names have the format + ``folders/{folder_id}`` (for example, ``folders/1234``). The + caller must have ``resourcemanager.folders.get`` permission on + the identified 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 resourcemanager_v3 + + def sample_get_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetFolderRequest( + name="name_value", + ) + + # Make the request + response = client.get_folder(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.GetFolderRequest, dict]): + The request object. The GetFolder request message. + name (str): + Required. The resource name of the folder to retrieve. + Must be of the form ``folders/{folder_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.resourcemanager_v3.types.Folder: + A folder in an organization's + resource hierarchy, used to organize + that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.GetFolderRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.GetFolderRequest): + request = folders.GetFolderRequest(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_folder] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_folders(self, + request: Optional[Union[folders.ListFoldersRequest, 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.ListFoldersPager: + r"""Lists the folders that are direct descendants of supplied parent + resource. ``list()`` provides a strongly consistent view of the + folders underneath the specified parent resource. ``list()`` + returns folders sorted based upon the (ascending) lexical + ordering of their display_name. The caller must have + ``resourcemanager.folders.list`` permission on the identified + parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_list_folders(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_folders(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.ListFoldersRequest, dict]): + The request object. The ListFolders request message. + parent (str): + Required. The resource name of the organization or + folder whose folders are being listed. Must be of the + form ``folders/{folder_id}`` or + ``organizations/{org_id}``. Access to this method is + controlled by checking the + ``resourcemanager.folders.list`` permission on the + ``parent``. + + 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.resourcemanager_v3.services.folders.pagers.ListFoldersPager: + The ListFolders response message. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.ListFoldersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.ListFoldersRequest): + request = folders.ListFoldersRequest(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_folders] + + # 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.ListFoldersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_folders(self, + request: Optional[Union[folders.SearchFoldersRequest, dict]] = None, + *, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchFoldersPager: + r"""Search for folders that match specific filter criteria. + ``search()`` provides an eventually consistent view of the + folders a user has access to which meet the specified filter + criteria. + + This will only return folders on which the caller has the + permission ``resourcemanager.folders.get``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_search_folders(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchFoldersRequest( + ) + + # Make the request + page_result = client.search_folders(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.SearchFoldersRequest, dict]): + The request object. The request message for searching + folders. + query (str): + Optional. Search criteria used to select the folders to + return. If no search criteria is specified then all + accessible folders will be returned. + + Query expressions can be used to restrict results based + upon displayName, state and parent, where the operators + ``=`` (``:``) ``NOT``, ``AND`` and ``OR`` can be used + along with the suffix wildcard symbol ``*``. + + The ``displayName`` field in a query expression should + use escaped quotes for values that include whitespace to + prevent unexpected behavior. + + :: + + | Field | Description | + |-------------------------|----------------------------------------| + | displayName | Filters by displayName. | + | parent | Filters by parent (for example: folders/123). | + | state, lifecycleState | Filters by state. | + + Some example queries are: + + - Query ``displayName=Test*`` returns Folder resources + whose display name starts with "Test". + - Query ``state=ACTIVE`` returns Folder resources with + ``state`` set to ``ACTIVE``. + - Query ``parent=folders/123`` returns Folder resources + that have ``folders/123`` as a parent resource. + - Query ``parent=folders/123 AND state=ACTIVE`` returns + active Folder resources that have ``folders/123`` as + a parent resource. + - Query ``displayName=\\"Test String\\"`` returns + Folder resources with display names that include both + "Test" and "String". + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersPager: + The response message for searching + folders. + 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([query]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.SearchFoldersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.SearchFoldersRequest): + request = folders.SearchFoldersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_folders] + + # 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.SearchFoldersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_folder(self, + request: Optional[Union[folders.CreateFolderRequest, dict]] = None, + *, + folder: Optional[folders.Folder] = 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 folder in the resource hierarchy. Returns an + ``Operation`` which can be used to track the progress of the + folder creation workflow. Upon success, the + ``Operation.response`` field will be populated with the created + Folder. + + In order to succeed, the addition of this new folder must not + violate the folder naming, height, or fanout constraints. + + - The folder's ``display_name`` must be distinct from all other + folders that share its parent. + - The addition of the folder must not cause the active folder + hierarchy to exceed a height of 10. Note, the full active + + deleted folder hierarchy is allowed to reach a height of 20; + this provides additional headroom when moving folders that + contain deleted folders. + - The addition of the folder must not cause the total number of + folders under its parent to exceed 300. + + If the operation fails due to a folder constraint violation, + some errors may be returned by the ``CreateFolder`` request, + with status code ``FAILED_PRECONDITION`` and an error + description. Other folder constraint violations will be + communicated in the ``Operation``, with the specific + ``PreconditionFailure`` returned in the details list in the + ``Operation.error`` field. + + The caller must have ``resourcemanager.folders.create`` + permission on the identified parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_create_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.CreateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.create_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.CreateFolderRequest, dict]): + The request object. The CreateFolder request message. + folder (google.cloud.resourcemanager_v3.types.Folder): + Required. The folder being created, + only the display name and parent will be + consulted. All other fields will be + ignored. + + This corresponds to the ``folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([folder]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.CreateFolderRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.CreateFolderRequest): + request = folders.CreateFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if folder is not None: + request.folder = folder + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_folder] + + # 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, + folders.Folder, + metadata_type=folders.CreateFolderMetadata, + ) + + # Done; return the response. + return response + + def update_folder(self, + request: Optional[Union[folders.UpdateFolderRequest, dict]] = None, + *, + folder: Optional[folders.Folder] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates a folder, changing its ``display_name``. Changes to the + folder ``display_name`` will be rejected if they violate either + the ``display_name`` formatting rules or the naming constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. + + The folder's ``display_name`` must start and end with a letter + or digit, may contain letters, digits, spaces, hyphens and + underscores and can be between 3 and 30 characters. This is + captured by the regular expression: + ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller + must have ``resourcemanager.folders.update`` permission on the + identified folder. + + If the update fails due to the unique name constraint then a + ``PreconditionFailure`` explaining this violation will be + returned in the Status.details field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_update_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.UpdateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.update_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.UpdateFolderRequest, dict]): + The request object. The request sent to the + [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] + method. + + Only the ``display_name`` field can be changed. All + other fields will be ignored. Use the + [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] + method to change the ``parent`` field. + folder (google.cloud.resourcemanager_v3.types.Folder): + Required. The new definition of the Folder. It must + include the ``name`` field, which cannot be changed. + + This corresponds to the ``folder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Fields to be updated. Only the + ``display_name`` can be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([folder, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.UpdateFolderRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.UpdateFolderRequest): + request = folders.UpdateFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if folder is not None: + request.folder = folder + 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_folder] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("folder.name", request.folder.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + folders.Folder, + metadata_type=folders.UpdateFolderMetadata, + ) + + # Done; return the response. + return response + + def move_folder(self, + request: Optional[Union[folders.MoveFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + destination_parent: 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"""Moves a folder under a new resource parent. Returns an + ``Operation`` which can be used to track the progress of the + folder move workflow. Upon success, the ``Operation.response`` + field will be populated with the moved folder. Upon failure, a + ``FolderOperationError`` categorizing the failure cause will be + returned - if the failure occurs synchronously then the + ``FolderOperationError`` will be returned in the + ``Status.details`` field. If it occurs asynchronously, then the + FolderOperation will be returned in the ``Operation.error`` + field. In addition, the ``Operation.metadata`` field will be + populated with a ``FolderOperation`` message as an aid to + stateless clients. Folder moves will be rejected if they violate + either the naming, height, or fanout constraints described in + the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.move`` permission on the folder's + current and proposed new parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_move_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveFolderRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.MoveFolderRequest, dict]): + The request object. The MoveFolder request message. + name (str): + Required. The resource name of the Folder to move. Must + be of the form folders/{folder_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + destination_parent (str): + Required. The resource name of the folder or + organization which should be the folder's new parent. + Must be of the form ``folders/{folder_id}`` or + ``organizations/{org_id}``. + + This corresponds to the ``destination_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick 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, destination_parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.MoveFolderRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.MoveFolderRequest): + request = folders.MoveFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if destination_parent is not None: + request.destination_parent = destination_parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move_folder] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + folders.Folder, + metadata_type=folders.MoveFolderMetadata, + ) + + # Done; return the response. + return response + + def delete_folder(self, + request: Optional[Union[folders.DeleteFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Requests deletion of a folder. The folder is moved into the + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state immediately, and is deleted approximately 30 days later. + This method may only be called on an empty folder, where a + folder is empty if it doesn't contain any folders or projects in + the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. If called on a folder in + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state the operation will result in a no-op success. The caller + must have ``resourcemanager.folders.delete`` permission on the + identified 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 resourcemanager_v3 + + def sample_delete_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.DeleteFolderRequest, dict]): + The request object. The DeleteFolder request message. + name (str): + Required. The resource name of the folder to be deleted. + Must be of the form ``folders/{folder_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.DeleteFolderRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.DeleteFolderRequest): + request = folders.DeleteFolderRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_folder] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + folders.Folder, + metadata_type=folders.DeleteFolderMetadata, + ) + + # Done; return the response. + return response + + def undelete_folder(self, + request: Optional[Union[folders.UndeleteFolderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Cancels the deletion request for a folder. This method may be + called on a folder in any state. If the folder is in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state the result will be a no-op success. In order to succeed, + the folder's parent must be in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. In addition, reintroducing the folder into the tree must + not violate folder naming, height, and fanout constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.undelete`` permission on the + identified 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 resourcemanager_v3 + + def sample_undelete_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.UndeleteFolderRequest, dict]): + The request object. The UndeleteFolder request message. + name (str): + Required. The resource name of the folder to undelete. + Must be of the form ``folders/{folder_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a folders.UndeleteFolderRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, folders.UndeleteFolderRequest): + request = folders.UndeleteFolderRequest(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.undelete_folder] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + folders.Folder, + metadata_type=folders.UndeleteFolderMetadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for a folder. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the folder's resource name, for + example: "folders/1234". The caller must have + ``resourcemanager.folders.getIamPolicy`` permission on the + identified 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 resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on a folder, replacing any + existing policy. The ``resource`` field should be the folder's + resource name, for example: "folders/1234". The caller must have + ``resourcemanager.folders.setIamPolicy`` permission on the + identified 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 resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified folder. + The ``resource`` field should be the folder's resource name, for + example: "folders/1234". + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "FoldersClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "FoldersClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py new file mode 100644 index 0000000..e4867b9 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.resourcemanager_v3.types import folders + + +class ListFoldersPager: + """A pager for iterating through ``list_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``folders`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFolders`` requests and continue to iterate + through the ``folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` + 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[..., folders.ListFoldersResponse], + request: folders.ListFoldersRequest, + response: folders.ListFoldersResponse, + *, + 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.resourcemanager_v3.types.ListFoldersRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListFoldersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = folders.ListFoldersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[folders.ListFoldersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[folders.Folder]: + for page in self.pages: + yield from page.folders + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFoldersAsyncPager: + """A pager for iterating through ``list_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``folders`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFolders`` requests and continue to iterate + through the ``folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` + 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[folders.ListFoldersResponse]], + request: folders.ListFoldersRequest, + response: folders.ListFoldersResponse, + *, + 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.resourcemanager_v3.types.ListFoldersRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListFoldersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = folders.ListFoldersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[folders.ListFoldersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[folders.Folder]: + async def async_generator(): + async for page in self.pages: + for response in page.folders: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchFoldersPager: + """A pager for iterating through ``search_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``folders`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchFolders`` requests and continue to iterate + through the ``folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` + 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[..., folders.SearchFoldersResponse], + request: folders.SearchFoldersRequest, + response: folders.SearchFoldersResponse, + *, + 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.resourcemanager_v3.types.SearchFoldersRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.SearchFoldersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = folders.SearchFoldersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[folders.SearchFoldersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[folders.Folder]: + for page in self.pages: + yield from page.folders + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchFoldersAsyncPager: + """A pager for iterating through ``search_folders`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``folders`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchFolders`` requests and continue to iterate + through the ``folders`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` + 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[folders.SearchFoldersResponse]], + request: folders.SearchFoldersRequest, + response: folders.SearchFoldersResponse, + *, + 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.resourcemanager_v3.types.SearchFoldersRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.SearchFoldersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = folders.SearchFoldersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[folders.SearchFoldersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[folders.Folder]: + async def async_generator(): + async for page in self.pages: + for response in page.folders: + 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/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py new file mode 100644 index 0000000..6156c27 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FoldersTransport +from .grpc import FoldersGrpcTransport +from .grpc_asyncio import FoldersGrpcAsyncIOTransport +from .rest import FoldersRestTransport +from .rest import FoldersRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FoldersTransport]] +_transport_registry['grpc'] = FoldersGrpcTransport +_transport_registry['grpc_asyncio'] = FoldersGrpcAsyncIOTransport +_transport_registry['rest'] = FoldersRestTransport + +__all__ = ( + 'FoldersTransport', + 'FoldersGrpcTransport', + 'FoldersGrpcAsyncIOTransport', + 'FoldersRestTransport', + 'FoldersRestInterceptor', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py new file mode 100644 index 0000000..3bcb757 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py @@ -0,0 +1,316 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 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.resourcemanager_v3.types import folders +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 FoldersTransport(abc.ABC): + """Abstract transport class for Folders.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_folder: gapic_v1.method.wrap_method( + self.get_folder, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_folders: gapic_v1.method.wrap_method( + self.list_folders, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_folders: gapic_v1.method.wrap_method( + self.search_folders, + default_timeout=60.0, + client_info=client_info, + ), + self.create_folder: gapic_v1.method.wrap_method( + self.create_folder, + default_timeout=60.0, + client_info=client_info, + ), + self.update_folder: gapic_v1.method.wrap_method( + self.update_folder, + default_timeout=60.0, + client_info=client_info, + ), + self.move_folder: gapic_v1.method.wrap_method( + self.move_folder, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_folder: gapic_v1.method.wrap_method( + self.delete_folder, + default_timeout=60.0, + client_info=client_info, + ), + self.undelete_folder: gapic_v1.method.wrap_method( + self.undelete_folder, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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 get_folder(self) -> Callable[ + [folders.GetFolderRequest], + Union[ + folders.Folder, + Awaitable[folders.Folder] + ]]: + raise NotImplementedError() + + @property + def list_folders(self) -> Callable[ + [folders.ListFoldersRequest], + Union[ + folders.ListFoldersResponse, + Awaitable[folders.ListFoldersResponse] + ]]: + raise NotImplementedError() + + @property + def search_folders(self) -> Callable[ + [folders.SearchFoldersRequest], + Union[ + folders.SearchFoldersResponse, + Awaitable[folders.SearchFoldersResponse] + ]]: + raise NotImplementedError() + + @property + def create_folder(self) -> Callable[ + [folders.CreateFolderRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_folder(self) -> Callable[ + [folders.UpdateFolderRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def move_folder(self) -> Callable[ + [folders.MoveFolderRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_folder(self) -> Callable[ + [folders.DeleteFolderRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undelete_folder(self) -> Callable[ + [folders.UndeleteFolderRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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__ = ( + 'FoldersTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py new file mode 100644 index 0000000..fe8fe0b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py @@ -0,0 +1,662 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3.types import folders +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 FoldersTransport, DEFAULT_CLIENT_INFO + + +class FoldersGrpcTransport(FoldersTransport): + """gRPC backend transport for Folders. + + Manages Cloud Platform folder resources. + Folders can be used to organize the resources under an + organization and to control the policies applied to groups of + resources. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudresourcemanager.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 get_folder(self) -> Callable[ + [folders.GetFolderRequest], + folders.Folder]: + r"""Return a callable for the get folder method over gRPC. + + Retrieves a folder identified by the supplied resource name. + Valid folder resource names have the format + ``folders/{folder_id}`` (for example, ``folders/1234``). The + caller must have ``resourcemanager.folders.get`` permission on + the identified folder. + + Returns: + Callable[[~.GetFolderRequest], + ~.Folder]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_folder' not in self._stubs: + self._stubs['get_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/GetFolder', + request_serializer=folders.GetFolderRequest.serialize, + response_deserializer=folders.Folder.deserialize, + ) + return self._stubs['get_folder'] + + @property + def list_folders(self) -> Callable[ + [folders.ListFoldersRequest], + folders.ListFoldersResponse]: + r"""Return a callable for the list folders method over gRPC. + + Lists the folders that are direct descendants of supplied parent + resource. ``list()`` provides a strongly consistent view of the + folders underneath the specified parent resource. ``list()`` + returns folders sorted based upon the (ascending) lexical + ordering of their display_name. The caller must have + ``resourcemanager.folders.list`` permission on the identified + parent. + + Returns: + Callable[[~.ListFoldersRequest], + ~.ListFoldersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_folders' not in self._stubs: + self._stubs['list_folders'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/ListFolders', + request_serializer=folders.ListFoldersRequest.serialize, + response_deserializer=folders.ListFoldersResponse.deserialize, + ) + return self._stubs['list_folders'] + + @property + def search_folders(self) -> Callable[ + [folders.SearchFoldersRequest], + folders.SearchFoldersResponse]: + r"""Return a callable for the search folders method over gRPC. + + Search for folders that match specific filter criteria. + ``search()`` provides an eventually consistent view of the + folders a user has access to which meet the specified filter + criteria. + + This will only return folders on which the caller has the + permission ``resourcemanager.folders.get``. + + Returns: + Callable[[~.SearchFoldersRequest], + ~.SearchFoldersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_folders' not in self._stubs: + self._stubs['search_folders'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/SearchFolders', + request_serializer=folders.SearchFoldersRequest.serialize, + response_deserializer=folders.SearchFoldersResponse.deserialize, + ) + return self._stubs['search_folders'] + + @property + def create_folder(self) -> Callable[ + [folders.CreateFolderRequest], + operations_pb2.Operation]: + r"""Return a callable for the create folder method over gRPC. + + Creates a folder in the resource hierarchy. Returns an + ``Operation`` which can be used to track the progress of the + folder creation workflow. Upon success, the + ``Operation.response`` field will be populated with the created + Folder. + + In order to succeed, the addition of this new folder must not + violate the folder naming, height, or fanout constraints. + + - The folder's ``display_name`` must be distinct from all other + folders that share its parent. + - The addition of the folder must not cause the active folder + hierarchy to exceed a height of 10. Note, the full active + + deleted folder hierarchy is allowed to reach a height of 20; + this provides additional headroom when moving folders that + contain deleted folders. + - The addition of the folder must not cause the total number of + folders under its parent to exceed 300. + + If the operation fails due to a folder constraint violation, + some errors may be returned by the ``CreateFolder`` request, + with status code ``FAILED_PRECONDITION`` and an error + description. Other folder constraint violations will be + communicated in the ``Operation``, with the specific + ``PreconditionFailure`` returned in the details list in the + ``Operation.error`` field. + + The caller must have ``resourcemanager.folders.create`` + permission on the identified parent. + + Returns: + Callable[[~.CreateFolderRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_folder' not in self._stubs: + self._stubs['create_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/CreateFolder', + request_serializer=folders.CreateFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_folder'] + + @property + def update_folder(self) -> Callable[ + [folders.UpdateFolderRequest], + operations_pb2.Operation]: + r"""Return a callable for the update folder method over gRPC. + + Updates a folder, changing its ``display_name``. Changes to the + folder ``display_name`` will be rejected if they violate either + the ``display_name`` formatting rules or the naming constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. + + The folder's ``display_name`` must start and end with a letter + or digit, may contain letters, digits, spaces, hyphens and + underscores and can be between 3 and 30 characters. This is + captured by the regular expression: + ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller + must have ``resourcemanager.folders.update`` permission on the + identified folder. + + If the update fails due to the unique name constraint then a + ``PreconditionFailure`` explaining this violation will be + returned in the Status.details field. + + Returns: + Callable[[~.UpdateFolderRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_folder' not in self._stubs: + self._stubs['update_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/UpdateFolder', + request_serializer=folders.UpdateFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_folder'] + + @property + def move_folder(self) -> Callable[ + [folders.MoveFolderRequest], + operations_pb2.Operation]: + r"""Return a callable for the move folder method over gRPC. + + Moves a folder under a new resource parent. Returns an + ``Operation`` which can be used to track the progress of the + folder move workflow. Upon success, the ``Operation.response`` + field will be populated with the moved folder. Upon failure, a + ``FolderOperationError`` categorizing the failure cause will be + returned - if the failure occurs synchronously then the + ``FolderOperationError`` will be returned in the + ``Status.details`` field. If it occurs asynchronously, then the + FolderOperation will be returned in the ``Operation.error`` + field. In addition, the ``Operation.metadata`` field will be + populated with a ``FolderOperation`` message as an aid to + stateless clients. Folder moves will be rejected if they violate + either the naming, height, or fanout constraints described in + the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.move`` permission on the folder's + current and proposed new parent. + + Returns: + Callable[[~.MoveFolderRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'move_folder' not in self._stubs: + self._stubs['move_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/MoveFolder', + request_serializer=folders.MoveFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_folder'] + + @property + def delete_folder(self) -> Callable[ + [folders.DeleteFolderRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete folder method over gRPC. + + Requests deletion of a folder. The folder is moved into the + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state immediately, and is deleted approximately 30 days later. + This method may only be called on an empty folder, where a + folder is empty if it doesn't contain any folders or projects in + the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. If called on a folder in + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state the operation will result in a no-op success. The caller + must have ``resourcemanager.folders.delete`` permission on the + identified folder. + + Returns: + Callable[[~.DeleteFolderRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_folder' not in self._stubs: + self._stubs['delete_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/DeleteFolder', + request_serializer=folders.DeleteFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_folder'] + + @property + def undelete_folder(self) -> Callable[ + [folders.UndeleteFolderRequest], + operations_pb2.Operation]: + r"""Return a callable for the undelete folder method over gRPC. + + Cancels the deletion request for a folder. This method may be + called on a folder in any state. If the folder is in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state the result will be a no-op success. In order to succeed, + the folder's parent must be in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. In addition, reintroducing the folder into the tree must + not violate folder naming, height, and fanout constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.undelete`` permission on the + identified folder. + + Returns: + Callable[[~.UndeleteFolderRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undelete_folder' not in self._stubs: + self._stubs['undelete_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/UndeleteFolder', + request_serializer=folders.UndeleteFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undelete_folder'] + + @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 access control policy for a folder. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the folder's resource name, for + example: "folders/1234". The caller must have + ``resourcemanager.folders.getIamPolicy`` permission on the + identified folder. + + 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.cloud.resourcemanager.v3.Folders/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on a folder, replacing any + existing policy. The ``resource`` field should be the folder's + resource name, for example: "folders/1234". The caller must have + ``resourcemanager.folders.setIamPolicy`` permission on the + identified folder. + + 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.cloud.resourcemanager.v3.Folders/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the specified folder. + The ``resource`` field should be the folder's resource name, for + example: "folders/1234". + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.Folders/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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'FoldersGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py new file mode 100644 index 0000000..0672f47 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py @@ -0,0 +1,661 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.resourcemanager_v3.types import folders +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 FoldersTransport, DEFAULT_CLIENT_INFO +from .grpc import FoldersGrpcTransport + + +class FoldersGrpcAsyncIOTransport(FoldersTransport): + """gRPC AsyncIO backend transport for Folders. + + Manages Cloud Platform folder resources. + Folders can be used to organize the resources under an + organization and to control the policies applied to groups of + resources. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_folder(self) -> Callable[ + [folders.GetFolderRequest], + Awaitable[folders.Folder]]: + r"""Return a callable for the get folder method over gRPC. + + Retrieves a folder identified by the supplied resource name. + Valid folder resource names have the format + ``folders/{folder_id}`` (for example, ``folders/1234``). The + caller must have ``resourcemanager.folders.get`` permission on + the identified folder. + + Returns: + Callable[[~.GetFolderRequest], + Awaitable[~.Folder]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_folder' not in self._stubs: + self._stubs['get_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/GetFolder', + request_serializer=folders.GetFolderRequest.serialize, + response_deserializer=folders.Folder.deserialize, + ) + return self._stubs['get_folder'] + + @property + def list_folders(self) -> Callable[ + [folders.ListFoldersRequest], + Awaitable[folders.ListFoldersResponse]]: + r"""Return a callable for the list folders method over gRPC. + + Lists the folders that are direct descendants of supplied parent + resource. ``list()`` provides a strongly consistent view of the + folders underneath the specified parent resource. ``list()`` + returns folders sorted based upon the (ascending) lexical + ordering of their display_name. The caller must have + ``resourcemanager.folders.list`` permission on the identified + parent. + + Returns: + Callable[[~.ListFoldersRequest], + Awaitable[~.ListFoldersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_folders' not in self._stubs: + self._stubs['list_folders'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/ListFolders', + request_serializer=folders.ListFoldersRequest.serialize, + response_deserializer=folders.ListFoldersResponse.deserialize, + ) + return self._stubs['list_folders'] + + @property + def search_folders(self) -> Callable[ + [folders.SearchFoldersRequest], + Awaitable[folders.SearchFoldersResponse]]: + r"""Return a callable for the search folders method over gRPC. + + Search for folders that match specific filter criteria. + ``search()`` provides an eventually consistent view of the + folders a user has access to which meet the specified filter + criteria. + + This will only return folders on which the caller has the + permission ``resourcemanager.folders.get``. + + Returns: + Callable[[~.SearchFoldersRequest], + Awaitable[~.SearchFoldersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_folders' not in self._stubs: + self._stubs['search_folders'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/SearchFolders', + request_serializer=folders.SearchFoldersRequest.serialize, + response_deserializer=folders.SearchFoldersResponse.deserialize, + ) + return self._stubs['search_folders'] + + @property + def create_folder(self) -> Callable[ + [folders.CreateFolderRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create folder method over gRPC. + + Creates a folder in the resource hierarchy. Returns an + ``Operation`` which can be used to track the progress of the + folder creation workflow. Upon success, the + ``Operation.response`` field will be populated with the created + Folder. + + In order to succeed, the addition of this new folder must not + violate the folder naming, height, or fanout constraints. + + - The folder's ``display_name`` must be distinct from all other + folders that share its parent. + - The addition of the folder must not cause the active folder + hierarchy to exceed a height of 10. Note, the full active + + deleted folder hierarchy is allowed to reach a height of 20; + this provides additional headroom when moving folders that + contain deleted folders. + - The addition of the folder must not cause the total number of + folders under its parent to exceed 300. + + If the operation fails due to a folder constraint violation, + some errors may be returned by the ``CreateFolder`` request, + with status code ``FAILED_PRECONDITION`` and an error + description. Other folder constraint violations will be + communicated in the ``Operation``, with the specific + ``PreconditionFailure`` returned in the details list in the + ``Operation.error`` field. + + The caller must have ``resourcemanager.folders.create`` + permission on the identified parent. + + Returns: + Callable[[~.CreateFolderRequest], + 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_folder' not in self._stubs: + self._stubs['create_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/CreateFolder', + request_serializer=folders.CreateFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_folder'] + + @property + def update_folder(self) -> Callable[ + [folders.UpdateFolderRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update folder method over gRPC. + + Updates a folder, changing its ``display_name``. Changes to the + folder ``display_name`` will be rejected if they violate either + the ``display_name`` formatting rules or the naming constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. + + The folder's ``display_name`` must start and end with a letter + or digit, may contain letters, digits, spaces, hyphens and + underscores and can be between 3 and 30 characters. This is + captured by the regular expression: + ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller + must have ``resourcemanager.folders.update`` permission on the + identified folder. + + If the update fails due to the unique name constraint then a + ``PreconditionFailure`` explaining this violation will be + returned in the Status.details field. + + Returns: + Callable[[~.UpdateFolderRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_folder' not in self._stubs: + self._stubs['update_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/UpdateFolder', + request_serializer=folders.UpdateFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_folder'] + + @property + def move_folder(self) -> Callable[ + [folders.MoveFolderRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the move folder method over gRPC. + + Moves a folder under a new resource parent. Returns an + ``Operation`` which can be used to track the progress of the + folder move workflow. Upon success, the ``Operation.response`` + field will be populated with the moved folder. Upon failure, a + ``FolderOperationError`` categorizing the failure cause will be + returned - if the failure occurs synchronously then the + ``FolderOperationError`` will be returned in the + ``Status.details`` field. If it occurs asynchronously, then the + FolderOperation will be returned in the ``Operation.error`` + field. In addition, the ``Operation.metadata`` field will be + populated with a ``FolderOperation`` message as an aid to + stateless clients. Folder moves will be rejected if they violate + either the naming, height, or fanout constraints described in + the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.move`` permission on the folder's + current and proposed new parent. + + Returns: + Callable[[~.MoveFolderRequest], + 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 'move_folder' not in self._stubs: + self._stubs['move_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/MoveFolder', + request_serializer=folders.MoveFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_folder'] + + @property + def delete_folder(self) -> Callable[ + [folders.DeleteFolderRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete folder method over gRPC. + + Requests deletion of a folder. The folder is moved into the + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state immediately, and is deleted approximately 30 days later. + This method may only be called on an empty folder, where a + folder is empty if it doesn't contain any folders or projects in + the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. If called on a folder in + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state the operation will result in a no-op success. The caller + must have ``resourcemanager.folders.delete`` permission on the + identified folder. + + Returns: + Callable[[~.DeleteFolderRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_folder' not in self._stubs: + self._stubs['delete_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/DeleteFolder', + request_serializer=folders.DeleteFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_folder'] + + @property + def undelete_folder(self) -> Callable[ + [folders.UndeleteFolderRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undelete folder method over gRPC. + + Cancels the deletion request for a folder. This method may be + called on a folder in any state. If the folder is in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state the result will be a no-op success. In order to succeed, + the folder's parent must be in the + [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] + state. In addition, reintroducing the folder into the tree must + not violate folder naming, height, and fanout constraints + described in the + [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] + documentation. The caller must have + ``resourcemanager.folders.undelete`` permission on the + identified folder. + + Returns: + Callable[[~.UndeleteFolderRequest], + 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 'undelete_folder' not in self._stubs: + self._stubs['undelete_folder'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Folders/UndeleteFolder', + request_serializer=folders.UndeleteFolderRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undelete_folder'] + + @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 access control policy for a folder. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the folder's resource name, for + example: "folders/1234". The caller must have + ``resourcemanager.folders.getIamPolicy`` permission on the + identified folder. + + 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.cloud.resourcemanager.v3.Folders/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on a folder, replacing any + existing policy. The ``resource`` field should be the folder's + resource name, for example: "folders/1234". The caller must have + ``resourcemanager.folders.setIamPolicy`` permission on the + identified folder. + + 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.cloud.resourcemanager.v3.Folders/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the specified folder. + The ``resource`` field should be the folder's resource name, for + example: "folders/1234". + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.Folders/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'FoldersGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py new file mode 100644 index 0000000..b45b76a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py @@ -0,0 +1,1650 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.resourcemanager_v3.types import folders +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 FoldersTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class FoldersRestInterceptor: + """Interceptor for Folders. + + 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 FoldersRestTransport. + + .. code-block:: python + class MyCustomFoldersInterceptor(FoldersRestInterceptor): + def pre_create_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_folders(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_folders(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_move_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_folders(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_folders(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_folder(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_folder(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_folder(self, response): + logging.log(f"Received response: {response}") + return response + + transport = FoldersRestTransport(interceptor=MyCustomFoldersInterceptor()) + client = FoldersClient(transport=transport) + + + """ + def pre_create_folder(self, request: folders.CreateFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.CreateFolderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_folder + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_create_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_folder + + Override in a subclass to manipulate the response + after it is returned by the Folders server but before + it is returned to user code. + """ + return response + def pre_delete_folder(self, request: folders.DeleteFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.DeleteFolderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_folder + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_delete_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_folder + + Override in a subclass to manipulate the response + after it is returned by the Folders server but before + it is returned to user code. + """ + return response + def pre_get_folder(self, request: folders.GetFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.GetFolderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_folder + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_get_folder(self, response: folders.Folder) -> folders.Folder: + """Post-rpc interceptor for get_folder + + Override in a subclass to manipulate the response + after it is returned by the Folders 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 Folders 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 Folders server but before + it is returned to user code. + """ + return response + def pre_list_folders(self, request: folders.ListFoldersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.ListFoldersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_folders + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_list_folders(self, response: folders.ListFoldersResponse) -> folders.ListFoldersResponse: + """Post-rpc interceptor for list_folders + + Override in a subclass to manipulate the response + after it is returned by the Folders server but before + it is returned to user code. + """ + return response + def pre_move_folder(self, request: folders.MoveFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.MoveFolderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for move_folder + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_move_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for move_folder + + Override in a subclass to manipulate the response + after it is returned by the Folders server but before + it is returned to user code. + """ + return response + def pre_search_folders(self, request: folders.SearchFoldersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.SearchFoldersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_folders + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_search_folders(self, response: folders.SearchFoldersResponse) -> folders.SearchFoldersResponse: + """Post-rpc interceptor for search_folders + + Override in a subclass to manipulate the response + after it is returned by the Folders 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 Folders 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 Folders 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 Folders 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 Folders server but before + it is returned to user code. + """ + return response + def pre_undelete_folder(self, request: folders.UndeleteFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.UndeleteFolderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undelete_folder + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_undelete_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_folder + + Override in a subclass to manipulate the response + after it is returned by the Folders server but before + it is returned to user code. + """ + return response + def pre_update_folder(self, request: folders.UpdateFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.UpdateFolderRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_folder + + Override in a subclass to manipulate the request or metadata + before they are sent to the Folders server. + """ + return request, metadata + + def post_update_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_folder + + Override in a subclass to manipulate the response + after it is returned by the Folders server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class FoldersRestStub: + _session: AuthorizedSession + _host: str + _interceptor: FoldersRestInterceptor + + +class FoldersRestTransport(FoldersTransport): + """REST backend transport for Folders. + + Manages Cloud Platform folder resources. + Folders can be used to organize the resources under an + organization and to control the policies applied to groups of + resources. + + 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 = 'cloudresourcemanager.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[FoldersRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or FoldersRestInterceptor() + 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': '/v3/{name=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="v3") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateFolder(FoldersRestStub): + def __hash__(self): + return hash("CreateFolder") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.CreateFolderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create folder method over HTTP. + + Args: + request (~.folders.CreateFolderRequest): + The request object. The CreateFolder request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/folders', + 'body': 'folder', + }, + ] + request, metadata = self._interceptor.pre_create_folder(request, metadata) + pb_request = folders.CreateFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_folder(resp) + return resp + + class _DeleteFolder(FoldersRestStub): + def __hash__(self): + return hash("DeleteFolder") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.DeleteFolderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete folder method over HTTP. + + Args: + request (~.folders.DeleteFolderRequest): + The request object. The DeleteFolder request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v3/{name=folders/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_folder(request, metadata) + pb_request = folders.DeleteFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_folder(resp) + return resp + + class _GetFolder(FoldersRestStub): + def __hash__(self): + return hash("GetFolder") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.GetFolderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> folders.Folder: + r"""Call the get folder method over HTTP. + + Args: + request (~.folders.GetFolderRequest): + The request object. The GetFolder request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.folders.Folder: + A folder in an organization's + resource hierarchy, used to organize + that organization's resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/{name=folders/*}', + }, + ] + request, metadata = self._interceptor.pre_get_folder(request, metadata) + pb_request = folders.GetFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = folders.Folder() + pb_resp = folders.Folder.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_folder(resp) + return resp + + class _GetIamPolicy(FoldersRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=folders/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _ListFolders(FoldersRestStub): + def __hash__(self): + return hash("ListFolders") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.ListFoldersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> folders.ListFoldersResponse: + r"""Call the list folders method over HTTP. + + Args: + request (~.folders.ListFoldersRequest): + The request object. The ListFolders request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.folders.ListFoldersResponse: + The ListFolders response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/folders', + }, + ] + request, metadata = self._interceptor.pre_list_folders(request, metadata) + pb_request = folders.ListFoldersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = folders.ListFoldersResponse() + pb_resp = folders.ListFoldersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_folders(resp) + return resp + + class _MoveFolder(FoldersRestStub): + def __hash__(self): + return hash("MoveFolder") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.MoveFolderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the move folder method over HTTP. + + Args: + request (~.folders.MoveFolderRequest): + The request object. The MoveFolder request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{name=folders/*}:move', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_move_folder(request, metadata) + pb_request = folders.MoveFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_move_folder(resp) + return resp + + class _SearchFolders(FoldersRestStub): + def __hash__(self): + return hash("SearchFolders") + + def __call__(self, + request: folders.SearchFoldersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> folders.SearchFoldersResponse: + r"""Call the search folders method over HTTP. + + Args: + request (~.folders.SearchFoldersRequest): + The request object. The request message for searching + folders. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.folders.SearchFoldersResponse: + The response message for searching + folders. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/folders:search', + }, + ] + request, metadata = self._interceptor.pre_search_folders(request, metadata) + pb_request = folders.SearchFoldersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = folders.SearchFoldersResponse() + pb_resp = folders.SearchFoldersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_folders(resp) + return resp + + class _SetIamPolicy(FoldersRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=folders/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(FoldersRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=folders/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UndeleteFolder(FoldersRestStub): + def __hash__(self): + return hash("UndeleteFolder") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.UndeleteFolderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undelete folder method over HTTP. + + Args: + request (~.folders.UndeleteFolderRequest): + The request object. The UndeleteFolder request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{name=folders/*}:undelete', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undelete_folder(request, metadata) + pb_request = folders.UndeleteFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undelete_folder(resp) + return resp + + class _UpdateFolder(FoldersRestStub): + def __hash__(self): + return hash("UpdateFolder") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: folders.UpdateFolderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update folder method over HTTP. + + Args: + request (~.folders.UpdateFolderRequest): + The request object. The request sent to the + [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] + method. + + Only the ``display_name`` field can be changed. All + other fields will be ignored. Use the + [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] + method to change the ``parent`` field. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v3/{folder.name=folders/*}', + 'body': 'folder', + }, + ] + request, metadata = self._interceptor.pre_update_folder(request, metadata) + pb_request = folders.UpdateFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_folder(resp) + return resp + + @property + def create_folder(self) -> Callable[ + [folders.CreateFolderRequest], + 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._CreateFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_folder(self) -> Callable[ + [folders.DeleteFolderRequest], + 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._DeleteFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_folder(self) -> Callable[ + [folders.GetFolderRequest], + folders.Folder]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_folders(self) -> Callable[ + [folders.ListFoldersRequest], + folders.ListFoldersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFolders(self._session, self._host, self._interceptor) # type: ignore + + @property + def move_folder(self) -> Callable[ + [folders.MoveFolderRequest], + 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._MoveFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_folders(self) -> Callable[ + [folders.SearchFoldersRequest], + folders.SearchFoldersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchFolders(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_folder(self) -> Callable[ + [folders.UndeleteFolderRequest], + 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._UndeleteFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_folder(self) -> Callable[ + [folders.UpdateFolderRequest], + 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._UpdateFolder(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'FoldersRestTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py new file mode 100644 index 0000000..f7d11d1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import OrganizationsClient +from .async_client import OrganizationsAsyncClient + +__all__ = ( + 'OrganizationsClient', + 'OrganizationsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py new file mode 100644 index 0000000..2cfc4eb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py @@ -0,0 +1,905 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.resourcemanager_v3.services.organizations import pagers +from google.cloud.resourcemanager_v3.types import organizations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OrganizationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OrganizationsGrpcAsyncIOTransport +from .client import OrganizationsClient + + +class OrganizationsAsyncClient: + """Allows users to manage their organization resources.""" + + _client: OrganizationsClient + + DEFAULT_ENDPOINT = OrganizationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OrganizationsClient.DEFAULT_MTLS_ENDPOINT + + organization_path = staticmethod(OrganizationsClient.organization_path) + parse_organization_path = staticmethod(OrganizationsClient.parse_organization_path) + common_billing_account_path = staticmethod(OrganizationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OrganizationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OrganizationsClient.common_folder_path) + parse_common_folder_path = staticmethod(OrganizationsClient.parse_common_folder_path) + common_organization_path = staticmethod(OrganizationsClient.common_organization_path) + parse_common_organization_path = staticmethod(OrganizationsClient.parse_common_organization_path) + common_project_path = staticmethod(OrganizationsClient.common_project_path) + parse_common_project_path = staticmethod(OrganizationsClient.parse_common_project_path) + common_location_path = staticmethod(OrganizationsClient.common_location_path) + parse_common_location_path = staticmethod(OrganizationsClient.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: + OrganizationsAsyncClient: The constructed client. + """ + return OrganizationsClient.from_service_account_info.__func__(OrganizationsAsyncClient, 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: + OrganizationsAsyncClient: The constructed client. + """ + return OrganizationsClient.from_service_account_file.__func__(OrganizationsAsyncClient, 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 OrganizationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> OrganizationsTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(OrganizationsClient).get_transport_class, type(OrganizationsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, OrganizationsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organizations client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.OrganizationsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = OrganizationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_organization(self, + request: Optional[Union[organizations.GetOrganizationRequest, 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]] = (), + ) -> organizations.Organization: + r"""Fetches an organization resource identified by the + specified resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_get_organization(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetOrganizationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]]): + The request object. The request sent to the ``GetOrganization`` method. The + ``name`` field is required. ``organization_id`` is no + longer accepted. + name (:class:`str`): + Required. The resource name of the Organization to + fetch. This is the organization's relative path in the + API, formatted as "organizations/[organizationId]". For + example, "organizations/1234". + + 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.resourcemanager_v3.types.Organization: + The root node in the resource + hierarchy to which a particular entity's + (a company, for example) resources + belong. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = organizations.GetOrganizationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_organization, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_organizations(self, + request: Optional[Union[organizations.SearchOrganizationsRequest, dict]] = None, + *, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchOrganizationsAsyncPager: + r"""Searches organization resources that are visible to the user and + satisfy the specified filter. This method returns organizations + in an unspecified order. New organizations do not necessarily + appear at the end of the results, and may take a small amount of + time to appear. + + Search will only return organizations on which the user has the + permission ``resourcemanager.organizations.get`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_search_organizations(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchOrganizationsRequest( + ) + + # Make the request + page_result = client.search_organizations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]]): + The request object. The request sent to the ``SearchOrganizations`` method. + query (:class:`str`): + Optional. An optional query string used to filter the + Organizations to return in the response. Query rules are + case-insensitive. + + :: + + | Field | Description | + |------------------|--------------------------------------------| + | directoryCustomerId, owner.directoryCustomerId | Filters by directory + customer id. | + | domain | Filters by domain. | + + Organizations may be queried by ``directoryCustomerId`` + or by ``domain``, where the domain is a G Suite domain, + for example: + + - Query ``directorycustomerid:123456789`` returns + Organization resources with + ``owner.directory_customer_id`` equal to + ``123456789``. + - Query ``domain:google.com`` returns Organization + resources corresponding to the domain ``google.com``. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsAsyncPager: + The response returned from the SearchOrganizations + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([query]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = organizations.SearchOrganizationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_organizations, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.SearchOrganizationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for an organization resource. The + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the organization's resource name, + for example: "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.getIamPolicy`` on the specified + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on an organization resource. + Replaces any existing policy. The ``resource`` field should be + the organization's resource name, for example: + "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.setIamPolicy`` on the specified + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the specified + organization. The ``resource`` field should be the + organization's resource name, for example: "organizations/123". + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._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), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "OrganizationsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py new file mode 100644 index 0000000..75783a9 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py @@ -0,0 +1,1096 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.resourcemanager_v3.services.organizations import pagers +from google.cloud.resourcemanager_v3.types import organizations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OrganizationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OrganizationsGrpcTransport +from .transports.grpc_asyncio import OrganizationsGrpcAsyncIOTransport +from .transports.rest import OrganizationsRestTransport + + +class OrganizationsClientMeta(type): + """Metaclass for the Organizations 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[OrganizationsTransport]] + _transport_registry["grpc"] = OrganizationsGrpcTransport + _transport_registry["grpc_asyncio"] = OrganizationsGrpcAsyncIOTransport + _transport_registry["rest"] = OrganizationsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[OrganizationsTransport]: + """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 OrganizationsClient(metaclass=OrganizationsClientMeta): + """Allows users to manage their organization resources.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + OrganizationsClient: 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: + OrganizationsClient: 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) -> OrganizationsTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def organization_path(organization: str,) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_organization_path(path: str) -> Dict[str,str]: + """Parses a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OrganizationsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organizations client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, OrganizationsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, OrganizationsTransport): + # transport is a OrganizationsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_organization(self, + request: Optional[Union[organizations.GetOrganizationRequest, 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]] = (), + ) -> organizations.Organization: + r"""Fetches an organization resource identified by the + specified resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_get_organization(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetOrganizationRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]): + The request object. The request sent to the ``GetOrganization`` method. The + ``name`` field is required. ``organization_id`` is no + longer accepted. + name (str): + Required. The resource name of the Organization to + fetch. This is the organization's relative path in the + API, formatted as "organizations/[organizationId]". For + example, "organizations/1234". + + 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.resourcemanager_v3.types.Organization: + The root node in the resource + hierarchy to which a particular entity's + (a company, for example) resources + belong. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a organizations.GetOrganizationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, organizations.GetOrganizationRequest): + request = organizations.GetOrganizationRequest(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_organization] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_organizations(self, + request: Optional[Union[organizations.SearchOrganizationsRequest, dict]] = None, + *, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchOrganizationsPager: + r"""Searches organization resources that are visible to the user and + satisfy the specified filter. This method returns organizations + in an unspecified order. New organizations do not necessarily + appear at the end of the results, and may take a small amount of + time to appear. + + Search will only return organizations on which the user has the + permission ``resourcemanager.organizations.get`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_search_organizations(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchOrganizationsRequest( + ) + + # Make the request + page_result = client.search_organizations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]): + The request object. The request sent to the ``SearchOrganizations`` method. + query (str): + Optional. An optional query string used to filter the + Organizations to return in the response. Query rules are + case-insensitive. + + :: + + | Field | Description | + |------------------|--------------------------------------------| + | directoryCustomerId, owner.directoryCustomerId | Filters by directory + customer id. | + | domain | Filters by domain. | + + Organizations may be queried by ``directoryCustomerId`` + or by ``domain``, where the domain is a G Suite domain, + for example: + + - Query ``directorycustomerid:123456789`` returns + Organization resources with + ``owner.directory_customer_id`` equal to + ``123456789``. + - Query ``domain:google.com`` returns Organization + resources corresponding to the domain ``google.com``. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsPager: + The response returned from the SearchOrganizations + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([query]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a organizations.SearchOrganizationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, organizations.SearchOrganizationsRequest): + request = organizations.SearchOrganizationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_organizations] + + # 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.SearchOrganizationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for an organization resource. The + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the organization's resource name, + for example: "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.getIamPolicy`` on the specified + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on an organization resource. + Replaces any existing policy. The ``resource`` field should be + the organization's resource name, for example: + "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.setIamPolicy`` on the specified + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the specified + organization. The ``resource`` field should be the + organization's resource name, for example: "organizations/123". + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "OrganizationsClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "OrganizationsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py new file mode 100644 index 0000000..16ab297 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.resourcemanager_v3.types import organizations + + +class SearchOrganizationsPager: + """A pager for iterating through ``search_organizations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``organizations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchOrganizations`` requests and continue to iterate + through the ``organizations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` + 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[..., organizations.SearchOrganizationsResponse], + request: organizations.SearchOrganizationsRequest, + response: organizations.SearchOrganizationsResponse, + *, + 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.resourcemanager_v3.types.SearchOrganizationsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = organizations.SearchOrganizationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[organizations.SearchOrganizationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[organizations.Organization]: + for page in self.pages: + yield from page.organizations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchOrganizationsAsyncPager: + """A pager for iterating through ``search_organizations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``organizations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchOrganizations`` requests and continue to iterate + through the ``organizations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` + 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[organizations.SearchOrganizationsResponse]], + request: organizations.SearchOrganizationsRequest, + response: organizations.SearchOrganizationsResponse, + *, + 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.resourcemanager_v3.types.SearchOrganizationsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = organizations.SearchOrganizationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[organizations.SearchOrganizationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[organizations.Organization]: + async def async_generator(): + async for page in self.pages: + for response in page.organizations: + 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/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py new file mode 100644 index 0000000..01ddf02 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import OrganizationsTransport +from .grpc import OrganizationsGrpcTransport +from .grpc_asyncio import OrganizationsGrpcAsyncIOTransport +from .rest import OrganizationsRestTransport +from .rest import OrganizationsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationsTransport]] +_transport_registry['grpc'] = OrganizationsGrpcTransport +_transport_registry['grpc_asyncio'] = OrganizationsGrpcAsyncIOTransport +_transport_registry['rest'] = OrganizationsRestTransport + +__all__ = ( + 'OrganizationsTransport', + 'OrganizationsGrpcTransport', + 'OrganizationsGrpcAsyncIOTransport', + 'OrganizationsRestTransport', + 'OrganizationsRestInterceptor', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py new file mode 100644 index 0000000..d7c76b3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 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.resourcemanager_v3.types import organizations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class OrganizationsTransport(abc.ABC): + """Abstract transport class for Organizations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_organization: gapic_v1.method.wrap_method( + self.get_organization, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_organizations: gapic_v1.method.wrap_method( + self.search_organizations, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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 get_organization(self) -> Callable[ + [organizations.GetOrganizationRequest], + Union[ + organizations.Organization, + Awaitable[organizations.Organization] + ]]: + raise NotImplementedError() + + @property + def search_organizations(self) -> Callable[ + [organizations.SearchOrganizationsRequest], + Union[ + organizations.SearchOrganizationsResponse, + Awaitable[organizations.SearchOrganizationsResponse] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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__ = ( + 'OrganizationsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py new file mode 100644 index 0000000..8797f8f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py @@ -0,0 +1,396 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3.types import organizations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import OrganizationsTransport, DEFAULT_CLIENT_INFO + + +class OrganizationsGrpcTransport(OrganizationsTransport): + """gRPC backend transport for Organizations. + + Allows users to manage their organization resources. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudresourcemanager.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 get_organization(self) -> Callable[ + [organizations.GetOrganizationRequest], + organizations.Organization]: + r"""Return a callable for the get organization method over gRPC. + + Fetches an organization resource identified by the + specified resource name. + + Returns: + Callable[[~.GetOrganizationRequest], + ~.Organization]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization' not in self._stubs: + self._stubs['get_organization'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Organizations/GetOrganization', + request_serializer=organizations.GetOrganizationRequest.serialize, + response_deserializer=organizations.Organization.deserialize, + ) + return self._stubs['get_organization'] + + @property + def search_organizations(self) -> Callable[ + [organizations.SearchOrganizationsRequest], + organizations.SearchOrganizationsResponse]: + r"""Return a callable for the search organizations method over gRPC. + + Searches organization resources that are visible to the user and + satisfy the specified filter. This method returns organizations + in an unspecified order. New organizations do not necessarily + appear at the end of the results, and may take a small amount of + time to appear. + + Search will only return organizations on which the user has the + permission ``resourcemanager.organizations.get`` + + Returns: + Callable[[~.SearchOrganizationsRequest], + ~.SearchOrganizationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_organizations' not in self._stubs: + self._stubs['search_organizations'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations', + request_serializer=organizations.SearchOrganizationsRequest.serialize, + response_deserializer=organizations.SearchOrganizationsResponse.deserialize, + ) + return self._stubs['search_organizations'] + + @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 access control policy for an organization resource. The + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the organization's resource name, + for example: "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.getIamPolicy`` on the specified + organization. + + 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.cloud.resourcemanager.v3.Organizations/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on an organization resource. + Replaces any existing policy. The ``resource`` field should be + the organization's resource name, for example: + "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.setIamPolicy`` on the specified + organization. + + 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.cloud.resourcemanager.v3.Organizations/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the specified + organization. The ``resource`` field should be the + organization's resource name, for example: "organizations/123". + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.Organizations/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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'OrganizationsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py new file mode 100644 index 0000000..10aa4f0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.resourcemanager_v3.types import organizations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import OrganizationsTransport, DEFAULT_CLIENT_INFO +from .grpc import OrganizationsGrpcTransport + + +class OrganizationsGrpcAsyncIOTransport(OrganizationsTransport): + """gRPC AsyncIO backend transport for Organizations. + + Allows users to manage their organization resources. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_organization(self) -> Callable[ + [organizations.GetOrganizationRequest], + Awaitable[organizations.Organization]]: + r"""Return a callable for the get organization method over gRPC. + + Fetches an organization resource identified by the + specified resource name. + + Returns: + Callable[[~.GetOrganizationRequest], + Awaitable[~.Organization]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_organization' not in self._stubs: + self._stubs['get_organization'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Organizations/GetOrganization', + request_serializer=organizations.GetOrganizationRequest.serialize, + response_deserializer=organizations.Organization.deserialize, + ) + return self._stubs['get_organization'] + + @property + def search_organizations(self) -> Callable[ + [organizations.SearchOrganizationsRequest], + Awaitable[organizations.SearchOrganizationsResponse]]: + r"""Return a callable for the search organizations method over gRPC. + + Searches organization resources that are visible to the user and + satisfy the specified filter. This method returns organizations + in an unspecified order. New organizations do not necessarily + appear at the end of the results, and may take a small amount of + time to appear. + + Search will only return organizations on which the user has the + permission ``resourcemanager.organizations.get`` + + Returns: + Callable[[~.SearchOrganizationsRequest], + Awaitable[~.SearchOrganizationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_organizations' not in self._stubs: + self._stubs['search_organizations'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations', + request_serializer=organizations.SearchOrganizationsRequest.serialize, + response_deserializer=organizations.SearchOrganizationsResponse.deserialize, + ) + return self._stubs['search_organizations'] + + @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 access control policy for an organization resource. The + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the organization's resource name, + for example: "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.getIamPolicy`` on the specified + organization. + + 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.cloud.resourcemanager.v3.Organizations/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on an organization resource. + Replaces any existing policy. The ``resource`` field should be + the organization's resource name, for example: + "organizations/123". + + Authorization requires the IAM permission + ``resourcemanager.organizations.setIamPolicy`` on the specified + organization. + + 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.cloud.resourcemanager.v3.Organizations/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the specified + organization. The ``resource`` field should be the + organization's resource name, for example: "organizations/123". + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.Organizations/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'OrganizationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py new file mode 100644 index 0000000..3acde45 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py @@ -0,0 +1,907 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.resourcemanager_v3.types import organizations +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +from .base import OrganizationsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class OrganizationsRestInterceptor: + """Interceptor for Organizations. + + 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 OrganizationsRestTransport. + + .. code-block:: python + class MyCustomOrganizationsInterceptor(OrganizationsRestInterceptor): + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_organization(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_organization(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_organizations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_organizations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OrganizationsRestTransport(interceptor=MyCustomOrganizationsInterceptor()) + client = OrganizationsClient(transport=transport) + + + """ + 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 Organizations 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 Organizations server but before + it is returned to user code. + """ + return response + def pre_get_organization(self, request: organizations.GetOrganizationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[organizations.GetOrganizationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_organization + + Override in a subclass to manipulate the request or metadata + before they are sent to the Organizations server. + """ + return request, metadata + + def post_get_organization(self, response: organizations.Organization) -> organizations.Organization: + """Post-rpc interceptor for get_organization + + Override in a subclass to manipulate the response + after it is returned by the Organizations server but before + it is returned to user code. + """ + return response + def pre_search_organizations(self, request: organizations.SearchOrganizationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[organizations.SearchOrganizationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_organizations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Organizations server. + """ + return request, metadata + + def post_search_organizations(self, response: organizations.SearchOrganizationsResponse) -> organizations.SearchOrganizationsResponse: + """Post-rpc interceptor for search_organizations + + Override in a subclass to manipulate the response + after it is returned by the Organizations 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 Organizations 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 Organizations 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 Organizations 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 Organizations server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class OrganizationsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OrganizationsRestInterceptor + + +class OrganizationsRestTransport(OrganizationsTransport): + """REST backend transport for Organizations. + + Allows users to manage their organization resources. + + 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 = 'cloudresourcemanager.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[OrganizationsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or OrganizationsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetIamPolicy(OrganizationsRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=organizations/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetOrganization(OrganizationsRestStub): + def __hash__(self): + return hash("GetOrganization") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: organizations.GetOrganizationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organizations.Organization: + r"""Call the get organization method over HTTP. + + Args: + request (~.organizations.GetOrganizationRequest): + The request object. The request sent to the ``GetOrganization`` method. The + ``name`` field is required. ``organization_id`` is no + longer accepted. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organizations.Organization: + The root node in the resource + hierarchy to which a particular entity's + (a company, for example) resources + belong. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/{name=organizations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_organization(request, metadata) + pb_request = organizations.GetOrganizationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organizations.Organization() + pb_resp = organizations.Organization.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_organization(resp) + return resp + + class _SearchOrganizations(OrganizationsRestStub): + def __hash__(self): + return hash("SearchOrganizations") + + def __call__(self, + request: organizations.SearchOrganizationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> organizations.SearchOrganizationsResponse: + r"""Call the search organizations method over HTTP. + + Args: + request (~.organizations.SearchOrganizationsRequest): + The request object. The request sent to the ``SearchOrganizations`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organizations.SearchOrganizationsResponse: + The response returned from the ``SearchOrganizations`` + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/organizations:search', + }, + ] + request, metadata = self._interceptor.pre_search_organizations(request, metadata) + pb_request = organizations.SearchOrganizationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = organizations.SearchOrganizationsResponse() + pb_resp = organizations.SearchOrganizationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_organizations(resp) + return resp + + class _SetIamPolicy(OrganizationsRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=organizations/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(OrganizationsRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=organizations/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_organization(self) -> Callable[ + [organizations.GetOrganizationRequest], + organizations.Organization]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetOrganization(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_organizations(self) -> Callable[ + [organizations.SearchOrganizationsRequest], + organizations.SearchOrganizationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchOrganizations(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'OrganizationsRestTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py new file mode 100644 index 0000000..7f60083 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ProjectsClient +from .async_client import ProjectsAsyncClient + +__all__ = ( + 'ProjectsClient', + 'ProjectsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py new file mode 100644 index 0000000..a89cf72 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py @@ -0,0 +1,1779 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.projects import pagers +from google.cloud.resourcemanager_v3.types import projects +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ProjectsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProjectsGrpcAsyncIOTransport +from .client import ProjectsClient + + +class ProjectsAsyncClient: + """Manages Google Cloud Projects.""" + + _client: ProjectsClient + + DEFAULT_ENDPOINT = ProjectsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProjectsClient.DEFAULT_MTLS_ENDPOINT + + project_path = staticmethod(ProjectsClient.project_path) + parse_project_path = staticmethod(ProjectsClient.parse_project_path) + common_billing_account_path = staticmethod(ProjectsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProjectsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProjectsClient.common_folder_path) + parse_common_folder_path = staticmethod(ProjectsClient.parse_common_folder_path) + common_organization_path = staticmethod(ProjectsClient.common_organization_path) + parse_common_organization_path = staticmethod(ProjectsClient.parse_common_organization_path) + common_project_path = staticmethod(ProjectsClient.common_project_path) + parse_common_project_path = staticmethod(ProjectsClient.parse_common_project_path) + common_location_path = staticmethod(ProjectsClient.common_location_path) + parse_common_location_path = staticmethod(ProjectsClient.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: + ProjectsAsyncClient: The constructed client. + """ + return ProjectsClient.from_service_account_info.__func__(ProjectsAsyncClient, 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: + ProjectsAsyncClient: The constructed client. + """ + return ProjectsClient.from_service_account_file.__func__(ProjectsAsyncClient, 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 ProjectsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProjectsTransport: + """Returns the transport used by the client instance. + + Returns: + ProjectsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProjectsClient).get_transport_class, type(ProjectsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProjectsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the projects client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProjectsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProjectsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_project(self, + request: Optional[Union[projects.GetProjectRequest, 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]] = (), + ) -> projects.Project: + r"""Retrieves the project identified by the specified ``name`` (for + example, ``projects/415104041262``). + + The caller must have ``resourcemanager.projects.get`` permission + for this 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 resourcemanager_v3 + + async def sample_get_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetProjectRequest( + name="name_value", + ) + + # Make the request + response = await client.get_project(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.GetProjectRequest, dict]]): + The request object. The request sent to the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + name (:class:`str`): + Required. The name of the project (for example, + ``projects/415104041262``). + + 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.resourcemanager_v3.types.Project: + A project is a high-level Google + Cloud entity. It is a container for + ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.GetProjectRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_project, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_projects(self, + request: Optional[Union[projects.ListProjectsRequest, 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.ListProjectsAsyncPager: + r"""Lists projects that are direct children of the specified folder + or organization resource. ``list()`` provides a strongly + consistent view of the projects underneath the specified parent + resource. ``list()`` returns projects sorted based upon the + (ascending) lexical ordering of their ``display_name``. The + caller must have ``resourcemanager.projects.list`` permission on + the identified parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_list_projects(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListProjectsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_projects(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.ListProjectsRequest, dict]]): + The request object. The request sent to the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + parent (:class:`str`): + Required. The name of the parent + resource to list projects under. + For example, setting this field to + 'folders/1234' would list all projects + directly under that folder. + + 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.resourcemanager_v3.services.projects.pagers.ListProjectsAsyncPager: + A page of the response received from the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + + A paginated response where more pages are available + has next_page_token set. This token can be used in a + subsequent request to retrieve the next request page. + + NOTE: A response may contain fewer elements than the + request page_size and still have a next_page_token. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.ListProjectsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_projects, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListProjectsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_projects(self, + request: Optional[Union[projects.SearchProjectsRequest, dict]] = None, + *, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchProjectsAsyncPager: + r"""Search for projects that the caller has both + ``resourcemanager.projects.get`` permission on, and also satisfy + the specified query. + + This method returns projects in an unspecified order. + + This method is eventually consistent with project mutations; + this means that a newly created project may not appear in the + results or recent updates to an existing project may not be + reflected in the results. To retrieve the latest state of a + project, use the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_search_projects(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchProjectsRequest( + ) + + # Make the request + page_result = client.search_projects(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchProjectsRequest, dict]]): + The request object. The request sent to the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + query (:class:`str`): + Optional. A query string for searching for projects that + the caller has ``resourcemanager.projects.get`` + permission to. If multiple fields are included in the + query, the it will return results that match any of the + fields. Some eligible fields are: + + :: + + | Field | Description | + |-------------------------|----------------------------------------------| + | displayName, name | Filters by displayName. | + | parent | Project's parent. (for example: folders/123, + organizations/*) Prefer parent field over parent.type and parent.id. | + | parent.type | Parent's type: `folder` or `organization`. | + | parent.id | Parent's id number (for example: 123) | + | id, projectId | Filters by projectId. | + | state, lifecycleState | Filters by state. | + | labels | Filters by label name or value. | + | labels. (where *key* is the name of a label) | Filters by label + name. | + + Search expressions are case insensitive. + + Some examples queries: + + :: + + | Query | Description | + |------------------|-----------------------------------------------------| + | name:how* | The project's name starts with "how". | + | name:Howl | The project's name is `Howl` or `howl`. | + | name:HOWL | Equivalent to above. | + | NAME:howl | Equivalent to above. | + | labels.color:* | The project has the label `color`. | + | labels.color:red | The project's label `color` has the value `red`. | + | labels.color:red labels.size:big | The project's label `color` has + the value `red` and its label `size` has the value `big`. | + + If no query is specified, the call will return projects + for which the user has the + ``resourcemanager.projects.get`` permission. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsAsyncPager: + A page of the response received from the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + + A paginated response where more pages are available + has next_page_token set. This token can be used in a + subsequent request to retrieve the next request page. + + 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([query]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.SearchProjectsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_projects, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.SearchProjectsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_project(self, + request: Optional[Union[projects.CreateProjectRequest, dict]] = None, + *, + project: Optional[projects.Project] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Request that a new project be created. The result is an + ``Operation`` which can be used to track the creation process. + This process usually takes a few seconds, but can sometimes take + much longer. The tracking ``Operation`` is automatically deleted + after a few hours, so there is no need to call + ``DeleteOperation``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_create_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateProjectRequest( + ) + + # Make the request + operation = client.create_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateProjectRequest, dict]]): + The request object. The request sent to the + [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] + method. + project (:class:`google.cloud.resourcemanager_v3.types.Project`): + Required. The Project to create. + + Project ID is required. If the requested ID is + unavailable, the request fails. + + If the ``parent`` field is set, the + ``resourcemanager.projects.create`` permission is + checked on the parent resource. If no parent is set and + the authorization credentials belong to an Organziation, + the parent will be set to that Organization. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.CreateProjectRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_project, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + projects.Project, + metadata_type=projects.CreateProjectMetadata, + ) + + # Done; return the response. + return response + + async def update_project(self, + request: Optional[Union[projects.UpdateProjectRequest, dict]] = None, + *, + project: Optional[projects.Project] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the ``display_name`` and labels of the project + identified by the specified ``name`` (for example, + ``projects/415104041262``). Deleting all labels requires an + update mask for labels field. + + The caller must have ``resourcemanager.projects.update`` + permission for this 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 resourcemanager_v3 + + async def sample_update_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UpdateProjectRequest( + ) + + # Make the request + operation = client.update_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateProjectRequest, dict]]): + The request object. The request sent to the + [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] + method. + + Only the ``display_name`` and ``labels`` fields can be + change. Use the + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method to change the ``parent`` field. + project (:class:`google.cloud.resourcemanager_v3.types.Project`): + Required. The new definition of the + project. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. An update mask to + selectively update fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.UpdateProjectRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_project, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project.name", request.project.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + projects.Project, + metadata_type=projects.UpdateProjectMetadata, + ) + + # Done; return the response. + return response + + async def move_project(self, + request: Optional[Union[projects.MoveProjectRequest, dict]] = None, + *, + name: Optional[str] = None, + destination_parent: 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"""Move a project to another place in your resource hierarchy, + under a new resource parent. + + Returns an operation which can be used to track the process of + the project move workflow. Upon success, the + ``Operation.response`` field will be populated with the moved + project. + + The caller must have ``resourcemanager.projects.update`` + permission on the project and have + ``resourcemanager.projects.move`` permission on the project's + current and proposed new parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_move_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveProjectRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.MoveProjectRequest, dict]]): + The request object. The request sent to + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method. + name (:class:`str`): + Required. The name of the project to + move. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + destination_parent (:class:`str`): + Required. The new parent to move the + Project under. + + This corresponds to the ``destination_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick 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, destination_parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.MoveProjectRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if destination_parent is not None: + request.destination_parent = destination_parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.move_project, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + projects.Project, + metadata_type=projects.MoveProjectMetadata, + ) + + # Done; return the response. + return response + + async def delete_project(self, + request: Optional[Union[projects.DeleteProjectRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Marks the project identified by the specified ``name`` (for + example, ``projects/415104041262``) for deletion. + + This method will only affect the project if it has a lifecycle + state of + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. + + This method changes the Project's lifecycle state from + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] + to + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. + The deletion starts at an unspecified time, at which point the + Project is no longer accessible. + + Until the deletion completes, you can check the lifecycle state + checked by retrieving the project with [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], and the + project remains visible to [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects]. + However, you cannot update the project. + + After the deletion completes, the project is not retrievable by + the [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], + [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects], and + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + methods. + + This method behaves idempotently, such that deleting a + ``DELETE_REQUESTED`` project will not cause an error, but also + won't do anything. + + The caller must have ``resourcemanager.projects.delete`` + permissions for this 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 resourcemanager_v3 + + async def sample_delete_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteProjectRequest, dict]]): + The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] + method. + name (:class:`str`): + Required. The name of the Project (for example, + ``projects/415104041262``). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.DeleteProjectRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_project, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + projects.Project, + metadata_type=projects.DeleteProjectMetadata, + ) + + # Done; return the response. + return response + + async def undelete_project(self, + request: Optional[Union[projects.UndeleteProjectRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores the project identified by the specified ``name`` (for + example, ``projects/415104041262``). You can only use this + method for a project that has a lifecycle state of + [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After + deletion starts, the project cannot be restored. + + The caller must have ``resourcemanager.projects.undelete`` + permission for this 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 resourcemanager_v3 + + async def sample_undelete_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]]): + The request object. The request sent to the [UndeleteProject] + [google.cloud.resourcemanager.v3.Projects.UndeleteProject] + method. + name (:class:`str`): + Required. The name of the project (for example, + ``projects/415104041262``). + + Required. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = projects.UndeleteProjectRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.undelete_project, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + projects.Project, + metadata_type=projects.UndeleteProjectMetadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Returns the IAM access control policy for the + specified project. Permission is denied if the policy or + the resource do not exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 for the specified project. + + CAUTION: This method will replace the existing policy, and + cannot be used to append additional IAM settings. + + Note: Removing service accounts from policies or changing their + roles can render services completely inoperable. It is important + to understand how the service account is being used before + removing or updating its roles. + + The following constraints apply when using ``setIamPolicy()``: + + - Project does not support ``allUsers`` and + ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of + a ``Policy``. + + - The owner role can be granted to a ``user``, + ``serviceAccount``, or a group that is part of an + organization. For example, group@myownpersonaldomain.com + could be added as an owner to a project in the + myownpersonaldomain.com organization, but not the + examplepetstore.com organization. + + - Service accounts can be made owners of a project directly + without any restrictions. However, to be added as an owner, a + user must be invited using the Cloud Platform console and + must accept the invitation. + + - A user cannot be granted the owner role using + ``setIamPolicy()``. The user must be granted the owner role + using the Cloud Platform Console and must explicitly accept + the invitation. + + - Invitations to grant the owner role cannot be sent using + ``setIamPolicy()``; they must be sent only using the Cloud + Platform Console. + + - Membership changes that leave the project without any owners + that have accepted the Terms of Service (ToS) will be + rejected. + + - If the project is not part of an organization, there must be + at least one owner who has accepted the Terms of Service + (ToS) agreement in the policy. Calling ``setIamPolicy()`` to + remove the last ToS-accepted owner from the policy will fail. + This restriction also applies to legacy projects that no + longer have owners who have accepted the ToS. Edits to IAM + policies will be rejected until the lack of a ToS-accepting + owner is rectified. + + - Calling this method requires enabling the App Engine Admin + API. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the + specified 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 resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._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), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ProjectsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py new file mode 100644 index 0000000..668cc88 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py @@ -0,0 +1,1964 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.projects import pagers +from google.cloud.resourcemanager_v3.types import projects +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ProjectsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProjectsGrpcTransport +from .transports.grpc_asyncio import ProjectsGrpcAsyncIOTransport +from .transports.rest import ProjectsRestTransport + + +class ProjectsClientMeta(type): + """Metaclass for the Projects 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[ProjectsTransport]] + _transport_registry["grpc"] = ProjectsGrpcTransport + _transport_registry["grpc_asyncio"] = ProjectsGrpcAsyncIOTransport + _transport_registry["rest"] = ProjectsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProjectsTransport]: + """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 ProjectsClient(metaclass=ProjectsClientMeta): + """Manages Google Cloud Projects.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProjectsClient: 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: + ProjectsClient: 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) -> ProjectsTransport: + """Returns the transport used by the client instance. + + Returns: + ProjectsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def project_path(project: str,) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_project_path(path: str) -> Dict[str,str]: + """Parses a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProjectsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the projects client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProjectsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProjectsTransport): + # transport is a ProjectsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_project(self, + request: Optional[Union[projects.GetProjectRequest, 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]] = (), + ) -> projects.Project: + r"""Retrieves the project identified by the specified ``name`` (for + example, ``projects/415104041262``). + + The caller must have ``resourcemanager.projects.get`` permission + for this 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 resourcemanager_v3 + + def sample_get_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetProjectRequest( + name="name_value", + ) + + # Make the request + response = client.get_project(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.GetProjectRequest, dict]): + The request object. The request sent to the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + name (str): + Required. The name of the project (for example, + ``projects/415104041262``). + + 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.resourcemanager_v3.types.Project: + A project is a high-level Google + Cloud entity. It is a container for + ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.GetProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.GetProjectRequest): + request = projects.GetProjectRequest(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_project] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_projects(self, + request: Optional[Union[projects.ListProjectsRequest, 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.ListProjectsPager: + r"""Lists projects that are direct children of the specified folder + or organization resource. ``list()`` provides a strongly + consistent view of the projects underneath the specified parent + resource. ``list()`` returns projects sorted based upon the + (ascending) lexical ordering of their ``display_name``. The + caller must have ``resourcemanager.projects.list`` permission on + the identified parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_list_projects(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListProjectsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_projects(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.ListProjectsRequest, dict]): + The request object. The request sent to the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + parent (str): + Required. The name of the parent + resource to list projects under. + For example, setting this field to + 'folders/1234' would list all projects + directly under that folder. + + 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.resourcemanager_v3.services.projects.pagers.ListProjectsPager: + A page of the response received from the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + + A paginated response where more pages are available + has next_page_token set. This token can be used in a + subsequent request to retrieve the next request page. + + NOTE: A response may contain fewer elements than the + request page_size and still have a next_page_token. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.ListProjectsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.ListProjectsRequest): + request = projects.ListProjectsRequest(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_projects] + + # 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.ListProjectsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_projects(self, + request: Optional[Union[projects.SearchProjectsRequest, dict]] = None, + *, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchProjectsPager: + r"""Search for projects that the caller has both + ``resourcemanager.projects.get`` permission on, and also satisfy + the specified query. + + This method returns projects in an unspecified order. + + This method is eventually consistent with project mutations; + this means that a newly created project may not appear in the + results or recent updates to an existing project may not be + reflected in the results. To retrieve the latest state of a + project, use the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_search_projects(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchProjectsRequest( + ) + + # Make the request + page_result = client.search_projects(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.SearchProjectsRequest, dict]): + The request object. The request sent to the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + query (str): + Optional. A query string for searching for projects that + the caller has ``resourcemanager.projects.get`` + permission to. If multiple fields are included in the + query, the it will return results that match any of the + fields. Some eligible fields are: + + :: + + | Field | Description | + |-------------------------|----------------------------------------------| + | displayName, name | Filters by displayName. | + | parent | Project's parent. (for example: folders/123, + organizations/*) Prefer parent field over parent.type and parent.id. | + | parent.type | Parent's type: `folder` or `organization`. | + | parent.id | Parent's id number (for example: 123) | + | id, projectId | Filters by projectId. | + | state, lifecycleState | Filters by state. | + | labels | Filters by label name or value. | + | labels. (where *key* is the name of a label) | Filters by label + name. | + + Search expressions are case insensitive. + + Some examples queries: + + :: + + | Query | Description | + |------------------|-----------------------------------------------------| + | name:how* | The project's name starts with "how". | + | name:Howl | The project's name is `Howl` or `howl`. | + | name:HOWL | Equivalent to above. | + | NAME:howl | Equivalent to above. | + | labels.color:* | The project has the label `color`. | + | labels.color:red | The project's label `color` has the value `red`. | + | labels.color:red labels.size:big | The project's label `color` has + the value `red` and its label `size` has the value `big`. | + + If no query is specified, the call will return projects + for which the user has the + ``resourcemanager.projects.get`` permission. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsPager: + A page of the response received from the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + + A paginated response where more pages are available + has next_page_token set. This token can be used in a + subsequent request to retrieve the next request page. + + 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([query]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.SearchProjectsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.SearchProjectsRequest): + request = projects.SearchProjectsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_projects] + + # 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.SearchProjectsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_project(self, + request: Optional[Union[projects.CreateProjectRequest, dict]] = None, + *, + project: Optional[projects.Project] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Request that a new project be created. The result is an + ``Operation`` which can be used to track the creation process. + This process usually takes a few seconds, but can sometimes take + much longer. The tracking ``Operation`` is automatically deleted + after a few hours, so there is no need to call + ``DeleteOperation``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_create_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateProjectRequest( + ) + + # Make the request + operation = client.create_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.CreateProjectRequest, dict]): + The request object. The request sent to the + [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] + method. + project (google.cloud.resourcemanager_v3.types.Project): + Required. The Project to create. + + Project ID is required. If the requested ID is + unavailable, the request fails. + + If the ``parent`` field is set, the + ``resourcemanager.projects.create`` permission is + checked on the parent resource. If no parent is set and + the authorization credentials belong to an Organziation, + the parent will be set to that Organization. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.CreateProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.CreateProjectRequest): + request = projects.CreateProjectRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_project] + + # 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, + projects.Project, + metadata_type=projects.CreateProjectMetadata, + ) + + # Done; return the response. + return response + + def update_project(self, + request: Optional[Union[projects.UpdateProjectRequest, dict]] = None, + *, + project: Optional[projects.Project] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the ``display_name`` and labels of the project + identified by the specified ``name`` (for example, + ``projects/415104041262``). Deleting all labels requires an + update mask for labels field. + + The caller must have ``resourcemanager.projects.update`` + permission for this 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 resourcemanager_v3 + + def sample_update_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UpdateProjectRequest( + ) + + # Make the request + operation = client.update_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.UpdateProjectRequest, dict]): + The request object. The request sent to the + [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] + method. + + Only the ``display_name`` and ``labels`` fields can be + change. Use the + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method to change the ``parent`` field. + project (google.cloud.resourcemanager_v3.types.Project): + Required. The new definition of the + project. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. An update mask to + selectively update fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.UpdateProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.UpdateProjectRequest): + request = projects.UpdateProjectRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + 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_project] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("project.name", request.project.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + projects.Project, + metadata_type=projects.UpdateProjectMetadata, + ) + + # Done; return the response. + return response + + def move_project(self, + request: Optional[Union[projects.MoveProjectRequest, dict]] = None, + *, + name: Optional[str] = None, + destination_parent: 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"""Move a project to another place in your resource hierarchy, + under a new resource parent. + + Returns an operation which can be used to track the process of + the project move workflow. Upon success, the + ``Operation.response`` field will be populated with the moved + project. + + The caller must have ``resourcemanager.projects.update`` + permission on the project and have + ``resourcemanager.projects.move`` permission on the project's + current and proposed new parent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_move_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveProjectRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.MoveProjectRequest, dict]): + The request object. The request sent to + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method. + name (str): + Required. The name of the project to + move. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + destination_parent (str): + Required. The new parent to move the + Project under. + + This corresponds to the ``destination_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick 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, destination_parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.MoveProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.MoveProjectRequest): + request = projects.MoveProjectRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if destination_parent is not None: + request.destination_parent = destination_parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.move_project] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + projects.Project, + metadata_type=projects.MoveProjectMetadata, + ) + + # Done; return the response. + return response + + def delete_project(self, + request: Optional[Union[projects.DeleteProjectRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Marks the project identified by the specified ``name`` (for + example, ``projects/415104041262``) for deletion. + + This method will only affect the project if it has a lifecycle + state of + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. + + This method changes the Project's lifecycle state from + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] + to + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. + The deletion starts at an unspecified time, at which point the + Project is no longer accessible. + + Until the deletion completes, you can check the lifecycle state + checked by retrieving the project with [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], and the + project remains visible to [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects]. + However, you cannot update the project. + + After the deletion completes, the project is not retrievable by + the [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], + [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects], and + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + methods. + + This method behaves idempotently, such that deleting a + ``DELETE_REQUESTED`` project will not cause an error, but also + won't do anything. + + The caller must have ``resourcemanager.projects.delete`` + permissions for this 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 resourcemanager_v3 + + def sample_delete_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.DeleteProjectRequest, dict]): + The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] + method. + name (str): + Required. The name of the Project (for example, + ``projects/415104041262``). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.DeleteProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.DeleteProjectRequest): + request = projects.DeleteProjectRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_project] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + projects.Project, + metadata_type=projects.DeleteProjectMetadata, + ) + + # Done; return the response. + return response + + def undelete_project(self, + request: Optional[Union[projects.UndeleteProjectRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores the project identified by the specified ``name`` (for + example, ``projects/415104041262``). You can only use this + method for a project that has a lifecycle state of + [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After + deletion starts, the project cannot be restored. + + The caller must have ``resourcemanager.projects.undelete`` + permission for this 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 resourcemanager_v3 + + def sample_undelete_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]): + The request object. The request sent to the [UndeleteProject] + [google.cloud.resourcemanager.v3.Projects.UndeleteProject] + method. + name (str): + Required. The name of the project (for example, + ``projects/415104041262``). + + Required. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a projects.UndeleteProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, projects.UndeleteProjectRequest): + request = projects.UndeleteProjectRequest(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.undelete_project] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + projects.Project, + metadata_type=projects.UndeleteProjectMetadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Returns the IAM access control policy for the + specified project. Permission is denied if the policy or + the resource do not exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 for the specified project. + + CAUTION: This method will replace the existing policy, and + cannot be used to append additional IAM settings. + + Note: Removing service accounts from policies or changing their + roles can render services completely inoperable. It is important + to understand how the service account is being used before + removing or updating its roles. + + The following constraints apply when using ``setIamPolicy()``: + + - Project does not support ``allUsers`` and + ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of + a ``Policy``. + + - The owner role can be granted to a ``user``, + ``serviceAccount``, or a group that is part of an + organization. For example, group@myownpersonaldomain.com + could be added as an owner to a project in the + myownpersonaldomain.com organization, but not the + examplepetstore.com organization. + + - Service accounts can be made owners of a project directly + without any restrictions. However, to be added as an owner, a + user must be invited using the Cloud Platform console and + must accept the invitation. + + - A user cannot be granted the owner role using + ``setIamPolicy()``. The user must be granted the owner role + using the Cloud Platform Console and must explicitly accept + the invitation. + + - Invitations to grant the owner role cannot be sent using + ``setIamPolicy()``; they must be sent only using the Cloud + Platform Console. + + - Membership changes that leave the project without any owners + that have accepted the Terms of Service (ToS) will be + rejected. + + - If the project is not part of an organization, there must be + at least one owner who has accepted the Terms of Service + (ToS) agreement in the policy. Calling ``setIamPolicy()`` to + remove the last ToS-accepted owner from the policy will fail. + This restriction also applies to legacy projects that no + longer have owners who have accepted the ToS. Edits to IAM + policies will be rejected until the lack of a ToS-accepting + owner is rectified. + + - Calling this method requires enabling the App Engine Admin + API. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the + specified 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 resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProjectsClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ProjectsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py new file mode 100644 index 0000000..a0cae99 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.resourcemanager_v3.types import projects + + +class ListProjectsPager: + """A pager for iterating through ``list_projects`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``projects`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProjects`` requests and continue to iterate + through the ``projects`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` + 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[..., projects.ListProjectsResponse], + request: projects.ListProjectsRequest, + response: projects.ListProjectsResponse, + *, + 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.resourcemanager_v3.types.ListProjectsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListProjectsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = projects.ListProjectsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[projects.ListProjectsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[projects.Project]: + for page in self.pages: + yield from page.projects + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProjectsAsyncPager: + """A pager for iterating through ``list_projects`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``projects`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProjects`` requests and continue to iterate + through the ``projects`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` + 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[projects.ListProjectsResponse]], + request: projects.ListProjectsRequest, + response: projects.ListProjectsResponse, + *, + 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.resourcemanager_v3.types.ListProjectsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListProjectsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = projects.ListProjectsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[projects.ListProjectsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[projects.Project]: + async def async_generator(): + async for page in self.pages: + for response in page.projects: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchProjectsPager: + """A pager for iterating through ``search_projects`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``projects`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchProjects`` requests and continue to iterate + through the ``projects`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` + 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[..., projects.SearchProjectsResponse], + request: projects.SearchProjectsRequest, + response: projects.SearchProjectsResponse, + *, + 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.resourcemanager_v3.types.SearchProjectsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.SearchProjectsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = projects.SearchProjectsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[projects.SearchProjectsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[projects.Project]: + for page in self.pages: + yield from page.projects + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchProjectsAsyncPager: + """A pager for iterating through ``search_projects`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``projects`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchProjects`` requests and continue to iterate + through the ``projects`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` + 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[projects.SearchProjectsResponse]], + request: projects.SearchProjectsRequest, + response: projects.SearchProjectsResponse, + *, + 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.resourcemanager_v3.types.SearchProjectsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.SearchProjectsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = projects.SearchProjectsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[projects.SearchProjectsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[projects.Project]: + async def async_generator(): + async for page in self.pages: + for response in page.projects: + 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/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py new file mode 100644 index 0000000..3cababc --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProjectsTransport +from .grpc import ProjectsGrpcTransport +from .grpc_asyncio import ProjectsGrpcAsyncIOTransport +from .rest import ProjectsRestTransport +from .rest import ProjectsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProjectsTransport]] +_transport_registry['grpc'] = ProjectsGrpcTransport +_transport_registry['grpc_asyncio'] = ProjectsGrpcAsyncIOTransport +_transport_registry['rest'] = ProjectsRestTransport + +__all__ = ( + 'ProjectsTransport', + 'ProjectsGrpcTransport', + 'ProjectsGrpcAsyncIOTransport', + 'ProjectsRestTransport', + 'ProjectsRestInterceptor', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py new file mode 100644 index 0000000..52b9140 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py @@ -0,0 +1,316 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 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.resourcemanager_v3.types import projects +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 ProjectsTransport(abc.ABC): + """Abstract transport class for Projects.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_project: gapic_v1.method.wrap_method( + self.get_project, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_projects: gapic_v1.method.wrap_method( + self.list_projects, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_projects: gapic_v1.method.wrap_method( + self.search_projects, + default_timeout=60.0, + client_info=client_info, + ), + self.create_project: gapic_v1.method.wrap_method( + self.create_project, + default_timeout=60.0, + client_info=client_info, + ), + self.update_project: gapic_v1.method.wrap_method( + self.update_project, + default_timeout=60.0, + client_info=client_info, + ), + self.move_project: gapic_v1.method.wrap_method( + self.move_project, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_project: gapic_v1.method.wrap_method( + self.delete_project, + default_timeout=60.0, + client_info=client_info, + ), + self.undelete_project: gapic_v1.method.wrap_method( + self.undelete_project, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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 get_project(self) -> Callable[ + [projects.GetProjectRequest], + Union[ + projects.Project, + Awaitable[projects.Project] + ]]: + raise NotImplementedError() + + @property + def list_projects(self) -> Callable[ + [projects.ListProjectsRequest], + Union[ + projects.ListProjectsResponse, + Awaitable[projects.ListProjectsResponse] + ]]: + raise NotImplementedError() + + @property + def search_projects(self) -> Callable[ + [projects.SearchProjectsRequest], + Union[ + projects.SearchProjectsResponse, + Awaitable[projects.SearchProjectsResponse] + ]]: + raise NotImplementedError() + + @property + def create_project(self) -> Callable[ + [projects.CreateProjectRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_project(self) -> Callable[ + [projects.UpdateProjectRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def move_project(self) -> Callable[ + [projects.MoveProjectRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_project(self) -> Callable[ + [projects.DeleteProjectRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def undelete_project(self) -> Callable[ + [projects.UndeleteProjectRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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__ = ( + 'ProjectsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py new file mode 100644 index 0000000..c963001 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py @@ -0,0 +1,684 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3.types import projects +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 ProjectsTransport, DEFAULT_CLIENT_INFO + + +class ProjectsGrpcTransport(ProjectsTransport): + """gRPC backend transport for Projects. + + Manages Google Cloud Projects. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudresourcemanager.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 get_project(self) -> Callable[ + [projects.GetProjectRequest], + projects.Project]: + r"""Return a callable for the get project method over gRPC. + + Retrieves the project identified by the specified ``name`` (for + example, ``projects/415104041262``). + + The caller must have ``resourcemanager.projects.get`` permission + for this project. + + Returns: + Callable[[~.GetProjectRequest], + ~.Project]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_project' not in self._stubs: + self._stubs['get_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/GetProject', + request_serializer=projects.GetProjectRequest.serialize, + response_deserializer=projects.Project.deserialize, + ) + return self._stubs['get_project'] + + @property + def list_projects(self) -> Callable[ + [projects.ListProjectsRequest], + projects.ListProjectsResponse]: + r"""Return a callable for the list projects method over gRPC. + + Lists projects that are direct children of the specified folder + or organization resource. ``list()`` provides a strongly + consistent view of the projects underneath the specified parent + resource. ``list()`` returns projects sorted based upon the + (ascending) lexical ordering of their ``display_name``. The + caller must have ``resourcemanager.projects.list`` permission on + the identified parent. + + Returns: + Callable[[~.ListProjectsRequest], + ~.ListProjectsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_projects' not in self._stubs: + self._stubs['list_projects'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/ListProjects', + request_serializer=projects.ListProjectsRequest.serialize, + response_deserializer=projects.ListProjectsResponse.deserialize, + ) + return self._stubs['list_projects'] + + @property + def search_projects(self) -> Callable[ + [projects.SearchProjectsRequest], + projects.SearchProjectsResponse]: + r"""Return a callable for the search projects method over gRPC. + + Search for projects that the caller has both + ``resourcemanager.projects.get`` permission on, and also satisfy + the specified query. + + This method returns projects in an unspecified order. + + This method is eventually consistent with project mutations; + this means that a newly created project may not appear in the + results or recent updates to an existing project may not be + reflected in the results. To retrieve the latest state of a + project, use the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + + Returns: + Callable[[~.SearchProjectsRequest], + ~.SearchProjectsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_projects' not in self._stubs: + self._stubs['search_projects'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/SearchProjects', + request_serializer=projects.SearchProjectsRequest.serialize, + response_deserializer=projects.SearchProjectsResponse.deserialize, + ) + return self._stubs['search_projects'] + + @property + def create_project(self) -> Callable[ + [projects.CreateProjectRequest], + operations_pb2.Operation]: + r"""Return a callable for the create project method over gRPC. + + Request that a new project be created. The result is an + ``Operation`` which can be used to track the creation process. + This process usually takes a few seconds, but can sometimes take + much longer. The tracking ``Operation`` is automatically deleted + after a few hours, so there is no need to call + ``DeleteOperation``. + + Returns: + Callable[[~.CreateProjectRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_project' not in self._stubs: + self._stubs['create_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/CreateProject', + request_serializer=projects.CreateProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_project'] + + @property + def update_project(self) -> Callable[ + [projects.UpdateProjectRequest], + operations_pb2.Operation]: + r"""Return a callable for the update project method over gRPC. + + Updates the ``display_name`` and labels of the project + identified by the specified ``name`` (for example, + ``projects/415104041262``). Deleting all labels requires an + update mask for labels field. + + The caller must have ``resourcemanager.projects.update`` + permission for this project. + + Returns: + Callable[[~.UpdateProjectRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_project' not in self._stubs: + self._stubs['update_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/UpdateProject', + request_serializer=projects.UpdateProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_project'] + + @property + def move_project(self) -> Callable[ + [projects.MoveProjectRequest], + operations_pb2.Operation]: + r"""Return a callable for the move project method over gRPC. + + Move a project to another place in your resource hierarchy, + under a new resource parent. + + Returns an operation which can be used to track the process of + the project move workflow. Upon success, the + ``Operation.response`` field will be populated with the moved + project. + + The caller must have ``resourcemanager.projects.update`` + permission on the project and have + ``resourcemanager.projects.move`` permission on the project's + current and proposed new parent. + + Returns: + Callable[[~.MoveProjectRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'move_project' not in self._stubs: + self._stubs['move_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/MoveProject', + request_serializer=projects.MoveProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_project'] + + @property + def delete_project(self) -> Callable[ + [projects.DeleteProjectRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete project method over gRPC. + + Marks the project identified by the specified ``name`` (for + example, ``projects/415104041262``) for deletion. + + This method will only affect the project if it has a lifecycle + state of + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. + + This method changes the Project's lifecycle state from + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] + to + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. + The deletion starts at an unspecified time, at which point the + Project is no longer accessible. + + Until the deletion completes, you can check the lifecycle state + checked by retrieving the project with [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], and the + project remains visible to [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects]. + However, you cannot update the project. + + After the deletion completes, the project is not retrievable by + the [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], + [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects], and + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + methods. + + This method behaves idempotently, such that deleting a + ``DELETE_REQUESTED`` project will not cause an error, but also + won't do anything. + + The caller must have ``resourcemanager.projects.delete`` + permissions for this project. + + Returns: + Callable[[~.DeleteProjectRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_project' not in self._stubs: + self._stubs['delete_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/DeleteProject', + request_serializer=projects.DeleteProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_project'] + + @property + def undelete_project(self) -> Callable[ + [projects.UndeleteProjectRequest], + operations_pb2.Operation]: + r"""Return a callable for the undelete project method over gRPC. + + Restores the project identified by the specified ``name`` (for + example, ``projects/415104041262``). You can only use this + method for a project that has a lifecycle state of + [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After + deletion starts, the project cannot be restored. + + The caller must have ``resourcemanager.projects.undelete`` + permission for this project. + + Returns: + Callable[[~.UndeleteProjectRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'undelete_project' not in self._stubs: + self._stubs['undelete_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/UndeleteProject', + request_serializer=projects.UndeleteProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undelete_project'] + + @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. + + Returns the IAM access control policy for the + specified project. Permission is denied if the policy or + the resource do not exist. + + 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.cloud.resourcemanager.v3.Projects/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 for the specified project. + + CAUTION: This method will replace the existing policy, and + cannot be used to append additional IAM settings. + + Note: Removing service accounts from policies or changing their + roles can render services completely inoperable. It is important + to understand how the service account is being used before + removing or updating its roles. + + The following constraints apply when using ``setIamPolicy()``: + + - Project does not support ``allUsers`` and + ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of + a ``Policy``. + + - The owner role can be granted to a ``user``, + ``serviceAccount``, or a group that is part of an + organization. For example, group@myownpersonaldomain.com + could be added as an owner to a project in the + myownpersonaldomain.com organization, but not the + examplepetstore.com organization. + + - Service accounts can be made owners of a project directly + without any restrictions. However, to be added as an owner, a + user must be invited using the Cloud Platform console and + must accept the invitation. + + - A user cannot be granted the owner role using + ``setIamPolicy()``. The user must be granted the owner role + using the Cloud Platform Console and must explicitly accept + the invitation. + + - Invitations to grant the owner role cannot be sent using + ``setIamPolicy()``; they must be sent only using the Cloud + Platform Console. + + - Membership changes that leave the project without any owners + that have accepted the Terms of Service (ToS) will be + rejected. + + - If the project is not part of an organization, there must be + at least one owner who has accepted the Terms of Service + (ToS) agreement in the policy. Calling ``setIamPolicy()`` to + remove the last ToS-accepted owner from the policy will fail. + This restriction also applies to legacy projects that no + longer have owners who have accepted the ToS. Edits to IAM + policies will be rejected until the lack of a ToS-accepting + owner is rectified. + + - Calling this method requires enabling the App Engine Admin + API. + + 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.cloud.resourcemanager.v3.Projects/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the + specified project. + + 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.cloud.resourcemanager.v3.Projects/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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProjectsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py new file mode 100644 index 0000000..127c24c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py @@ -0,0 +1,683 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.resourcemanager_v3.types import projects +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 ProjectsTransport, DEFAULT_CLIENT_INFO +from .grpc import ProjectsGrpcTransport + + +class ProjectsGrpcAsyncIOTransport(ProjectsTransport): + """gRPC AsyncIO backend transport for Projects. + + Manages Google Cloud Projects. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_project(self) -> Callable[ + [projects.GetProjectRequest], + Awaitable[projects.Project]]: + r"""Return a callable for the get project method over gRPC. + + Retrieves the project identified by the specified ``name`` (for + example, ``projects/415104041262``). + + The caller must have ``resourcemanager.projects.get`` permission + for this project. + + Returns: + Callable[[~.GetProjectRequest], + Awaitable[~.Project]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_project' not in self._stubs: + self._stubs['get_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/GetProject', + request_serializer=projects.GetProjectRequest.serialize, + response_deserializer=projects.Project.deserialize, + ) + return self._stubs['get_project'] + + @property + def list_projects(self) -> Callable[ + [projects.ListProjectsRequest], + Awaitable[projects.ListProjectsResponse]]: + r"""Return a callable for the list projects method over gRPC. + + Lists projects that are direct children of the specified folder + or organization resource. ``list()`` provides a strongly + consistent view of the projects underneath the specified parent + resource. ``list()`` returns projects sorted based upon the + (ascending) lexical ordering of their ``display_name``. The + caller must have ``resourcemanager.projects.list`` permission on + the identified parent. + + Returns: + Callable[[~.ListProjectsRequest], + Awaitable[~.ListProjectsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_projects' not in self._stubs: + self._stubs['list_projects'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/ListProjects', + request_serializer=projects.ListProjectsRequest.serialize, + response_deserializer=projects.ListProjectsResponse.deserialize, + ) + return self._stubs['list_projects'] + + @property + def search_projects(self) -> Callable[ + [projects.SearchProjectsRequest], + Awaitable[projects.SearchProjectsResponse]]: + r"""Return a callable for the search projects method over gRPC. + + Search for projects that the caller has both + ``resourcemanager.projects.get`` permission on, and also satisfy + the specified query. + + This method returns projects in an unspecified order. + + This method is eventually consistent with project mutations; + this means that a newly created project may not appear in the + results or recent updates to an existing project may not be + reflected in the results. To retrieve the latest state of a + project, use the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + + Returns: + Callable[[~.SearchProjectsRequest], + Awaitable[~.SearchProjectsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_projects' not in self._stubs: + self._stubs['search_projects'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/SearchProjects', + request_serializer=projects.SearchProjectsRequest.serialize, + response_deserializer=projects.SearchProjectsResponse.deserialize, + ) + return self._stubs['search_projects'] + + @property + def create_project(self) -> Callable[ + [projects.CreateProjectRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create project method over gRPC. + + Request that a new project be created. The result is an + ``Operation`` which can be used to track the creation process. + This process usually takes a few seconds, but can sometimes take + much longer. The tracking ``Operation`` is automatically deleted + after a few hours, so there is no need to call + ``DeleteOperation``. + + Returns: + Callable[[~.CreateProjectRequest], + 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_project' not in self._stubs: + self._stubs['create_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/CreateProject', + request_serializer=projects.CreateProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_project'] + + @property + def update_project(self) -> Callable[ + [projects.UpdateProjectRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update project method over gRPC. + + Updates the ``display_name`` and labels of the project + identified by the specified ``name`` (for example, + ``projects/415104041262``). Deleting all labels requires an + update mask for labels field. + + The caller must have ``resourcemanager.projects.update`` + permission for this project. + + Returns: + Callable[[~.UpdateProjectRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_project' not in self._stubs: + self._stubs['update_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/UpdateProject', + request_serializer=projects.UpdateProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_project'] + + @property + def move_project(self) -> Callable[ + [projects.MoveProjectRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the move project method over gRPC. + + Move a project to another place in your resource hierarchy, + under a new resource parent. + + Returns an operation which can be used to track the process of + the project move workflow. Upon success, the + ``Operation.response`` field will be populated with the moved + project. + + The caller must have ``resourcemanager.projects.update`` + permission on the project and have + ``resourcemanager.projects.move`` permission on the project's + current and proposed new parent. + + Returns: + Callable[[~.MoveProjectRequest], + 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 'move_project' not in self._stubs: + self._stubs['move_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/MoveProject', + request_serializer=projects.MoveProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['move_project'] + + @property + def delete_project(self) -> Callable[ + [projects.DeleteProjectRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete project method over gRPC. + + Marks the project identified by the specified ``name`` (for + example, ``projects/415104041262``) for deletion. + + This method will only affect the project if it has a lifecycle + state of + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. + + This method changes the Project's lifecycle state from + [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] + to + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. + The deletion starts at an unspecified time, at which point the + Project is no longer accessible. + + Until the deletion completes, you can check the lifecycle state + checked by retrieving the project with [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], and the + project remains visible to [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects]. + However, you cannot update the project. + + After the deletion completes, the project is not retrievable by + the [GetProject] + [google.cloud.resourcemanager.v3.Projects.GetProject], + [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects], and + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + methods. + + This method behaves idempotently, such that deleting a + ``DELETE_REQUESTED`` project will not cause an error, but also + won't do anything. + + The caller must have ``resourcemanager.projects.delete`` + permissions for this project. + + Returns: + Callable[[~.DeleteProjectRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_project' not in self._stubs: + self._stubs['delete_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/DeleteProject', + request_serializer=projects.DeleteProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_project'] + + @property + def undelete_project(self) -> Callable[ + [projects.UndeleteProjectRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the undelete project method over gRPC. + + Restores the project identified by the specified ``name`` (for + example, ``projects/415104041262``). You can only use this + method for a project that has a lifecycle state of + [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After + deletion starts, the project cannot be restored. + + The caller must have ``resourcemanager.projects.undelete`` + permission for this project. + + Returns: + Callable[[~.UndeleteProjectRequest], + 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 'undelete_project' not in self._stubs: + self._stubs['undelete_project'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.Projects/UndeleteProject', + request_serializer=projects.UndeleteProjectRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['undelete_project'] + + @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. + + Returns the IAM access control policy for the + specified project. Permission is denied if the policy or + the resource do not exist. + + 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.cloud.resourcemanager.v3.Projects/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 for the specified project. + + CAUTION: This method will replace the existing policy, and + cannot be used to append additional IAM settings. + + Note: Removing service accounts from policies or changing their + roles can render services completely inoperable. It is important + to understand how the service account is being used before + removing or updating its roles. + + The following constraints apply when using ``setIamPolicy()``: + + - Project does not support ``allUsers`` and + ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of + a ``Policy``. + + - The owner role can be granted to a ``user``, + ``serviceAccount``, or a group that is part of an + organization. For example, group@myownpersonaldomain.com + could be added as an owner to a project in the + myownpersonaldomain.com organization, but not the + examplepetstore.com organization. + + - Service accounts can be made owners of a project directly + without any restrictions. However, to be added as an owner, a + user must be invited using the Cloud Platform console and + must accept the invitation. + + - A user cannot be granted the owner role using + ``setIamPolicy()``. The user must be granted the owner role + using the Cloud Platform Console and must explicitly accept + the invitation. + + - Invitations to grant the owner role cannot be sent using + ``setIamPolicy()``; they must be sent only using the Cloud + Platform Console. + + - Membership changes that leave the project without any owners + that have accepted the Terms of Service (ToS) will be + rejected. + + - If the project is not part of an organization, there must be + at least one owner who has accepted the Terms of Service + (ToS) agreement in the policy. Calling ``setIamPolicy()`` to + remove the last ToS-accepted owner from the policy will fail. + This restriction also applies to legacy projects that no + longer have owners who have accepted the ToS. Edits to IAM + policies will be rejected until the lack of a ToS-accepting + owner is rectified. + + - Calling this method requires enabling the App Engine Admin + API. + + 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.cloud.resourcemanager.v3.Projects/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the + specified project. + + 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.cloud.resourcemanager.v3.Projects/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ProjectsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py new file mode 100644 index 0000000..ee5e055 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py @@ -0,0 +1,1676 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.resourcemanager_v3.types import projects +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 ProjectsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ProjectsRestInterceptor: + """Interceptor for Projects. + + 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 ProjectsRestTransport. + + .. code-block:: python + class MyCustomProjectsInterceptor(ProjectsRestInterceptor): + def pre_create_project(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_project(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_project(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_project(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_project(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_project(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_projects(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_projects(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_move_project(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move_project(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_projects(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_projects(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_project(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_project(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_project(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_project(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProjectsRestTransport(interceptor=MyCustomProjectsInterceptor()) + client = ProjectsClient(transport=transport) + + + """ + def pre_create_project(self, request: projects.CreateProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.CreateProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_project + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_create_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_project + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + def pre_delete_project(self, request: projects.DeleteProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.DeleteProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_project + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_delete_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_project + + Override in a subclass to manipulate the response + after it is returned by the Projects 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 Projects 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 Projects server but before + it is returned to user code. + """ + return response + def pre_get_project(self, request: projects.GetProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.GetProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_project + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_get_project(self, response: projects.Project) -> projects.Project: + """Post-rpc interceptor for get_project + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + def pre_list_projects(self, request: projects.ListProjectsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.ListProjectsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_projects + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_list_projects(self, response: projects.ListProjectsResponse) -> projects.ListProjectsResponse: + """Post-rpc interceptor for list_projects + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + def pre_move_project(self, request: projects.MoveProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.MoveProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for move_project + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_move_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for move_project + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + def pre_search_projects(self, request: projects.SearchProjectsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.SearchProjectsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_projects + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_search_projects(self, response: projects.SearchProjectsResponse) -> projects.SearchProjectsResponse: + """Post-rpc interceptor for search_projects + + Override in a subclass to manipulate the response + after it is returned by the Projects 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 Projects 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 Projects 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 Projects 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 Projects server but before + it is returned to user code. + """ + return response + def pre_undelete_project(self, request: projects.UndeleteProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.UndeleteProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undelete_project + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_undelete_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_project + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + def pre_update_project(self, request: projects.UpdateProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.UpdateProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_project + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_update_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_project + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ProjectsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProjectsRestInterceptor + + +class ProjectsRestTransport(ProjectsTransport): + """REST backend transport for Projects. + + Manages Google Cloud Projects. + + 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 = 'cloudresourcemanager.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[ProjectsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ProjectsRestInterceptor() + 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': '/v3/{name=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="v3") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateProject(ProjectsRestStub): + def __hash__(self): + return hash("CreateProject") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.CreateProjectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create project method over HTTP. + + Args: + request (~.projects.CreateProjectRequest): + The request object. The request sent to the + [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/projects', + 'body': 'project', + }, + ] + request, metadata = self._interceptor.pre_create_project(request, metadata) + pb_request = projects.CreateProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_project(resp) + return resp + + class _DeleteProject(ProjectsRestStub): + def __hash__(self): + return hash("DeleteProject") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.DeleteProjectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete project method over HTTP. + + Args: + request (~.projects.DeleteProjectRequest): + The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v3/{name=projects/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_project(request, metadata) + pb_request = projects.DeleteProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_project(resp) + return resp + + class _GetIamPolicy(ProjectsRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=projects/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetProject(ProjectsRestStub): + def __hash__(self): + return hash("GetProject") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.GetProjectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> projects.Project: + r"""Call the get project method over HTTP. + + Args: + request (~.projects.GetProjectRequest): + The request object. The request sent to the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.projects.Project: + A project is a high-level Google + Cloud entity. It is a container for + ACLs, APIs, App Engine Apps, VMs, and + other Google Cloud Platform resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/{name=projects/*}', + }, + ] + request, metadata = self._interceptor.pre_get_project(request, metadata) + pb_request = projects.GetProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = projects.Project() + pb_resp = projects.Project.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_project(resp) + return resp + + class _ListProjects(ProjectsRestStub): + def __hash__(self): + return hash("ListProjects") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.ListProjectsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> projects.ListProjectsResponse: + r"""Call the list projects method over HTTP. + + Args: + request (~.projects.ListProjectsRequest): + The request object. The request sent to the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.projects.ListProjectsResponse: + A page of the response received from the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + + A paginated response where more pages are available has + ``next_page_token`` set. This token can be used in a + subsequent request to retrieve the next request page. + + NOTE: A response may contain fewer elements than the + request ``page_size`` and still have a + ``next_page_token``. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/projects', + }, + ] + request, metadata = self._interceptor.pre_list_projects(request, metadata) + pb_request = projects.ListProjectsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = projects.ListProjectsResponse() + pb_resp = projects.ListProjectsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_projects(resp) + return resp + + class _MoveProject(ProjectsRestStub): + def __hash__(self): + return hash("MoveProject") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.MoveProjectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the move project method over HTTP. + + Args: + request (~.projects.MoveProjectRequest): + The request object. The request sent to + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{name=projects/*}:move', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_move_project(request, metadata) + pb_request = projects.MoveProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_move_project(resp) + return resp + + class _SearchProjects(ProjectsRestStub): + def __hash__(self): + return hash("SearchProjects") + + def __call__(self, + request: projects.SearchProjectsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> projects.SearchProjectsResponse: + r"""Call the search projects method over HTTP. + + Args: + request (~.projects.SearchProjectsRequest): + The request object. The request sent to the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.projects.SearchProjectsResponse: + A page of the response received from the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + + A paginated response where more pages are available has + ``next_page_token`` set. This token can be used in a + subsequent request to retrieve the next request page. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/projects:search', + }, + ] + request, metadata = self._interceptor.pre_search_projects(request, metadata) + pb_request = projects.SearchProjectsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = projects.SearchProjectsResponse() + pb_resp = projects.SearchProjectsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_projects(resp) + return resp + + class _SetIamPolicy(ProjectsRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=projects/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(ProjectsRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=projects/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UndeleteProject(ProjectsRestStub): + def __hash__(self): + return hash("UndeleteProject") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.UndeleteProjectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the undelete project method over HTTP. + + Args: + request (~.projects.UndeleteProjectRequest): + The request object. The request sent to the [UndeleteProject] + [google.cloud.resourcemanager.v3.Projects.UndeleteProject] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{name=projects/*}:undelete', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_undelete_project(request, metadata) + pb_request = projects.UndeleteProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undelete_project(resp) + return resp + + class _UpdateProject(ProjectsRestStub): + def __hash__(self): + return hash("UpdateProject") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: projects.UpdateProjectRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update project method over HTTP. + + Args: + request (~.projects.UpdateProjectRequest): + The request object. The request sent to the + [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] + method. + + Only the ``display_name`` and ``labels`` fields can be + change. Use the + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method to change the ``parent`` field. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v3/{project.name=projects/*}', + 'body': 'project', + }, + ] + request, metadata = self._interceptor.pre_update_project(request, metadata) + pb_request = projects.UpdateProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_project(resp) + return resp + + @property + def create_project(self) -> Callable[ + [projects.CreateProjectRequest], + 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._CreateProject(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_project(self) -> Callable[ + [projects.DeleteProjectRequest], + 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._DeleteProject(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_project(self) -> Callable[ + [projects.GetProjectRequest], + projects.Project]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProject(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_projects(self) -> Callable[ + [projects.ListProjectsRequest], + projects.ListProjectsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProjects(self._session, self._host, self._interceptor) # type: ignore + + @property + def move_project(self) -> Callable[ + [projects.MoveProjectRequest], + 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._MoveProject(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_projects(self) -> Callable[ + [projects.SearchProjectsRequest], + projects.SearchProjectsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SearchProjects(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_project(self) -> Callable[ + [projects.UndeleteProjectRequest], + 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._UndeleteProject(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_project(self) -> Callable[ + [projects.UpdateProjectRequest], + 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._UpdateProject(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ProjectsRestTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py new file mode 100644 index 0000000..6c815d1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import TagBindingsClient +from .async_client import TagBindingsAsyncClient + +__all__ = ( + 'TagBindingsClient', + 'TagBindingsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py new file mode 100644 index 0000000..ba25499 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py @@ -0,0 +1,556 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.tag_bindings import pagers +from google.cloud.resourcemanager_v3.types import tag_bindings +from google.protobuf import empty_pb2 # type: ignore +from .transports.base import TagBindingsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TagBindingsGrpcAsyncIOTransport +from .client import TagBindingsClient + + +class TagBindingsAsyncClient: + """Allow users to create and manage TagBindings between + TagValues and different cloud resources throughout the GCP + resource hierarchy. + """ + + _client: TagBindingsClient + + DEFAULT_ENDPOINT = TagBindingsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TagBindingsClient.DEFAULT_MTLS_ENDPOINT + + tag_binding_path = staticmethod(TagBindingsClient.tag_binding_path) + parse_tag_binding_path = staticmethod(TagBindingsClient.parse_tag_binding_path) + common_billing_account_path = staticmethod(TagBindingsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TagBindingsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TagBindingsClient.common_folder_path) + parse_common_folder_path = staticmethod(TagBindingsClient.parse_common_folder_path) + common_organization_path = staticmethod(TagBindingsClient.common_organization_path) + parse_common_organization_path = staticmethod(TagBindingsClient.parse_common_organization_path) + common_project_path = staticmethod(TagBindingsClient.common_project_path) + parse_common_project_path = staticmethod(TagBindingsClient.parse_common_project_path) + common_location_path = staticmethod(TagBindingsClient.common_location_path) + parse_common_location_path = staticmethod(TagBindingsClient.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: + TagBindingsAsyncClient: The constructed client. + """ + return TagBindingsClient.from_service_account_info.__func__(TagBindingsAsyncClient, 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: + TagBindingsAsyncClient: The constructed client. + """ + return TagBindingsClient.from_service_account_file.__func__(TagBindingsAsyncClient, 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 TagBindingsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TagBindingsTransport: + """Returns the transport used by the client instance. + + Returns: + TagBindingsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TagBindingsClient).get_transport_class, type(TagBindingsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, TagBindingsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tag bindings client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TagBindingsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = TagBindingsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_tag_bindings(self, + request: Optional[Union[tag_bindings.ListTagBindingsRequest, 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.ListTagBindingsAsyncPager: + r"""Lists the TagBindings for the given cloud resource, as specified + with ``parent``. + + NOTE: The ``parent`` field is expected to be a full resource + name: + https://cloud.google.com/apis/design/resource_names#full_resource_name + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_list_tag_bindings(): + # Create a client + client = resourcemanager_v3.TagBindingsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagBindingsRequest, dict]]): + The request object. The request message to list all + TagBindings for a parent. + parent (:class:`str`): + Required. The full resource name of a + resource for which you want to list + existing TagBindings. E.g. + "//cloudresourcemanager.googleapis.com/projects/123" + + 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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsAsyncPager: + The ListTagBindings response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_bindings.ListTagBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_tag_bindings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListTagBindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_tag_binding(self, + request: Optional[Union[tag_bindings.CreateTagBindingRequest, dict]] = None, + *, + tag_binding: Optional[tag_bindings.TagBinding] = 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 TagBinding between a TagValue and a cloud + resource (currently project, folder, or organization). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_create_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateTagBindingRequest( + ) + + # Make the request + operation = client.create_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagBindingRequest, dict]]): + The request object. The request message to create a + TagBinding. + tag_binding (:class:`google.cloud.resourcemanager_v3.types.TagBinding`): + Required. The TagBinding to be + created. + + This corresponds to the ``tag_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.TagBinding` A TagBinding represents a connection between a TagValue and a cloud + resource (currently project, folder, or + organization). Once a TagBinding is created, the + TagValue is applied to all the descendants of the + cloud resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_binding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_bindings.CreateTagBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_binding is not None: + request.tag_binding = tag_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_tag_binding, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + tag_bindings.TagBinding, + metadata_type=tag_bindings.CreateTagBindingMetadata, + ) + + # Done; return the response. + return response + + async def delete_tag_binding(self, + request: Optional[Union[tag_bindings.DeleteTagBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a TagBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_delete_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest, dict]]): + The request object. The request message to delete a + TagBinding. + name (:class:`str`): + Required. The name of the TagBinding. This is a String + of the form: ``tagBindings/{id}`` (e.g. + ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_bindings.DeleteTagBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_tag_binding, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=tag_bindings.DeleteTagBindingMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "TagBindingsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py new file mode 100644 index 0000000..662246a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py @@ -0,0 +1,754 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.tag_bindings import pagers +from google.cloud.resourcemanager_v3.types import tag_bindings +from google.protobuf import empty_pb2 # type: ignore +from .transports.base import TagBindingsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TagBindingsGrpcTransport +from .transports.grpc_asyncio import TagBindingsGrpcAsyncIOTransport +from .transports.rest import TagBindingsRestTransport + + +class TagBindingsClientMeta(type): + """Metaclass for the TagBindings 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[TagBindingsTransport]] + _transport_registry["grpc"] = TagBindingsGrpcTransport + _transport_registry["grpc_asyncio"] = TagBindingsGrpcAsyncIOTransport + _transport_registry["rest"] = TagBindingsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TagBindingsTransport]: + """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 TagBindingsClient(metaclass=TagBindingsClientMeta): + """Allow users to create and manage TagBindings between + TagValues and different cloud resources throughout the GCP + resource hierarchy. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TagBindingsClient: 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: + TagBindingsClient: 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) -> TagBindingsTransport: + """Returns the transport used by the client instance. + + Returns: + TagBindingsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def tag_binding_path(tag_binding: str,) -> str: + """Returns a fully-qualified tag_binding string.""" + return "tagBindings/{tag_binding}".format(tag_binding=tag_binding, ) + + @staticmethod + def parse_tag_binding_path(path: str) -> Dict[str,str]: + """Parses a tag_binding path into its component segments.""" + m = re.match(r"^tagBindings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TagBindingsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tag bindings client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TagBindingsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TagBindingsTransport): + # transport is a TagBindingsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_tag_bindings(self, + request: Optional[Union[tag_bindings.ListTagBindingsRequest, 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.ListTagBindingsPager: + r"""Lists the TagBindings for the given cloud resource, as specified + with ``parent``. + + NOTE: The ``parent`` field is expected to be a full resource + name: + https://cloud.google.com/apis/design/resource_names#full_resource_name + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_list_tag_bindings(): + # Create a client + client = resourcemanager_v3.TagBindingsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.ListTagBindingsRequest, dict]): + The request object. The request message to list all + TagBindings for a parent. + parent (str): + Required. The full resource name of a + resource for which you want to list + existing TagBindings. E.g. + "//cloudresourcemanager.googleapis.com/projects/123" + + 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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsPager: + The ListTagBindings response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_bindings.ListTagBindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_bindings.ListTagBindingsRequest): + request = tag_bindings.ListTagBindingsRequest(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_tag_bindings] + + # 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.ListTagBindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_tag_binding(self, + request: Optional[Union[tag_bindings.CreateTagBindingRequest, dict]] = None, + *, + tag_binding: Optional[tag_bindings.TagBinding] = 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 TagBinding between a TagValue and a cloud + resource (currently project, folder, or organization). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_create_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateTagBindingRequest( + ) + + # Make the request + operation = client.create_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.CreateTagBindingRequest, dict]): + The request object. The request message to create a + TagBinding. + tag_binding (google.cloud.resourcemanager_v3.types.TagBinding): + Required. The TagBinding to be + created. + + This corresponds to the ``tag_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.TagBinding` A TagBinding represents a connection between a TagValue and a cloud + resource (currently project, folder, or + organization). Once a TagBinding is created, the + TagValue is applied to all the descendants of the + cloud resource. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_binding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_bindings.CreateTagBindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_bindings.CreateTagBindingRequest): + request = tag_bindings.CreateTagBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_binding is not None: + request.tag_binding = tag_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_binding] + + # 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, + tag_bindings.TagBinding, + metadata_type=tag_bindings.CreateTagBindingMetadata, + ) + + # Done; return the response. + return response + + def delete_tag_binding(self, + request: Optional[Union[tag_bindings.DeleteTagBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a TagBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_delete_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest, dict]): + The request object. The request message to delete a + TagBinding. + name (str): + Required. The name of the TagBinding. This is a String + of the form: ``tagBindings/{id}`` (e.g. + ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_bindings.DeleteTagBindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_bindings.DeleteTagBindingRequest): + request = tag_bindings.DeleteTagBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=tag_bindings.DeleteTagBindingMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "TagBindingsClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "TagBindingsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py new file mode 100644 index 0000000..427ffc2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.resourcemanager_v3.types import tag_bindings + + +class ListTagBindingsPager: + """A pager for iterating through ``list_tag_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tag_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTagBindings`` requests and continue to iterate + through the ``tag_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` + 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[..., tag_bindings.ListTagBindingsResponse], + request: tag_bindings.ListTagBindingsRequest, + response: tag_bindings.ListTagBindingsResponse, + *, + 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.resourcemanager_v3.types.ListTagBindingsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListTagBindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tag_bindings.ListTagBindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tag_bindings.ListTagBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tag_bindings.TagBinding]: + for page in self.pages: + yield from page.tag_bindings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagBindingsAsyncPager: + """A pager for iterating through ``list_tag_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tag_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTagBindings`` requests and continue to iterate + through the ``tag_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` + 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[tag_bindings.ListTagBindingsResponse]], + request: tag_bindings.ListTagBindingsRequest, + response: tag_bindings.ListTagBindingsResponse, + *, + 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.resourcemanager_v3.types.ListTagBindingsRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListTagBindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tag_bindings.ListTagBindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tag_bindings.ListTagBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[tag_bindings.TagBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.tag_bindings: + 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/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py new file mode 100644 index 0000000..94fccb4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import TagBindingsTransport +from .grpc import TagBindingsGrpcTransport +from .grpc_asyncio import TagBindingsGrpcAsyncIOTransport +from .rest import TagBindingsRestTransport +from .rest import TagBindingsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TagBindingsTransport]] +_transport_registry['grpc'] = TagBindingsGrpcTransport +_transport_registry['grpc_asyncio'] = TagBindingsGrpcAsyncIOTransport +_transport_registry['rest'] = TagBindingsRestTransport + +__all__ = ( + 'TagBindingsTransport', + 'TagBindingsGrpcTransport', + 'TagBindingsGrpcAsyncIOTransport', + 'TagBindingsRestTransport', + 'TagBindingsRestInterceptor', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py new file mode 100644 index 0000000..e1cdac1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 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.resourcemanager_v3.types import tag_bindings +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class TagBindingsTransport(abc.ABC): + """Abstract transport class for TagBindings.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_tag_bindings: gapic_v1.method.wrap_method( + self.list_tag_bindings, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_tag_binding: gapic_v1.method.wrap_method( + self.create_tag_binding, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_tag_binding: gapic_v1.method.wrap_method( + self.delete_tag_binding, + default_timeout=60.0, + 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 list_tag_bindings(self) -> Callable[ + [tag_bindings.ListTagBindingsRequest], + Union[ + tag_bindings.ListTagBindingsResponse, + Awaitable[tag_bindings.ListTagBindingsResponse] + ]]: + raise NotImplementedError() + + @property + def create_tag_binding(self) -> Callable[ + [tag_bindings.CreateTagBindingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_tag_binding(self) -> Callable[ + [tag_bindings.DeleteTagBindingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TagBindingsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py new file mode 100644 index 0000000..f183ccf --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py @@ -0,0 +1,343 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3.types import tag_bindings +from google.longrunning import operations_pb2 # type: ignore +from .base import TagBindingsTransport, DEFAULT_CLIENT_INFO + + +class TagBindingsGrpcTransport(TagBindingsTransport): + """gRPC backend transport for TagBindings. + + Allow users to create and manage TagBindings between + TagValues and different cloud resources throughout the GCP + resource hierarchy. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudresourcemanager.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 list_tag_bindings(self) -> Callable[ + [tag_bindings.ListTagBindingsRequest], + tag_bindings.ListTagBindingsResponse]: + r"""Return a callable for the list tag bindings method over gRPC. + + Lists the TagBindings for the given cloud resource, as specified + with ``parent``. + + NOTE: The ``parent`` field is expected to be a full resource + name: + https://cloud.google.com/apis/design/resource_names#full_resource_name + + Returns: + Callable[[~.ListTagBindingsRequest], + ~.ListTagBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_bindings' not in self._stubs: + self._stubs['list_tag_bindings'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagBindings/ListTagBindings', + request_serializer=tag_bindings.ListTagBindingsRequest.serialize, + response_deserializer=tag_bindings.ListTagBindingsResponse.deserialize, + ) + return self._stubs['list_tag_bindings'] + + @property + def create_tag_binding(self) -> Callable[ + [tag_bindings.CreateTagBindingRequest], + operations_pb2.Operation]: + r"""Return a callable for the create tag binding method over gRPC. + + Creates a TagBinding between a TagValue and a cloud + resource (currently project, folder, or organization). + + Returns: + Callable[[~.CreateTagBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_binding' not in self._stubs: + self._stubs['create_tag_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagBindings/CreateTagBinding', + request_serializer=tag_bindings.CreateTagBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tag_binding'] + + @property + def delete_tag_binding(self) -> Callable[ + [tag_bindings.DeleteTagBindingRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete tag binding method over gRPC. + + Deletes a TagBinding. + + Returns: + Callable[[~.DeleteTagBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_tag_binding' not in self._stubs: + self._stubs['delete_tag_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagBindings/DeleteTagBinding', + request_serializer=tag_bindings.DeleteTagBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tag_binding'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TagBindingsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py new file mode 100644 index 0000000..2de3983 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py @@ -0,0 +1,342 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.resourcemanager_v3.types import tag_bindings +from google.longrunning import operations_pb2 # type: ignore +from .base import TagBindingsTransport, DEFAULT_CLIENT_INFO +from .grpc import TagBindingsGrpcTransport + + +class TagBindingsGrpcAsyncIOTransport(TagBindingsTransport): + """gRPC AsyncIO backend transport for TagBindings. + + Allow users to create and manage TagBindings between + TagValues and different cloud resources throughout the GCP + resource hierarchy. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_tag_bindings(self) -> Callable[ + [tag_bindings.ListTagBindingsRequest], + Awaitable[tag_bindings.ListTagBindingsResponse]]: + r"""Return a callable for the list tag bindings method over gRPC. + + Lists the TagBindings for the given cloud resource, as specified + with ``parent``. + + NOTE: The ``parent`` field is expected to be a full resource + name: + https://cloud.google.com/apis/design/resource_names#full_resource_name + + Returns: + Callable[[~.ListTagBindingsRequest], + Awaitable[~.ListTagBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_bindings' not in self._stubs: + self._stubs['list_tag_bindings'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagBindings/ListTagBindings', + request_serializer=tag_bindings.ListTagBindingsRequest.serialize, + response_deserializer=tag_bindings.ListTagBindingsResponse.deserialize, + ) + return self._stubs['list_tag_bindings'] + + @property + def create_tag_binding(self) -> Callable[ + [tag_bindings.CreateTagBindingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create tag binding method over gRPC. + + Creates a TagBinding between a TagValue and a cloud + resource (currently project, folder, or organization). + + Returns: + Callable[[~.CreateTagBindingRequest], + 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_tag_binding' not in self._stubs: + self._stubs['create_tag_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagBindings/CreateTagBinding', + request_serializer=tag_bindings.CreateTagBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tag_binding'] + + @property + def delete_tag_binding(self) -> Callable[ + [tag_bindings.DeleteTagBindingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete tag binding method over gRPC. + + Deletes a TagBinding. + + Returns: + Callable[[~.DeleteTagBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_tag_binding' not in self._stubs: + self._stubs['delete_tag_binding'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagBindings/DeleteTagBinding', + request_serializer=tag_bindings.DeleteTagBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tag_binding'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'TagBindingsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py new file mode 100644 index 0000000..2d36c96 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py @@ -0,0 +1,558 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.resourcemanager_v3.types import tag_bindings +from google.longrunning import operations_pb2 # type: ignore + +from .base import TagBindingsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class TagBindingsRestInterceptor: + """Interceptor for TagBindings. + + 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 TagBindingsRestTransport. + + .. code-block:: python + class MyCustomTagBindingsInterceptor(TagBindingsRestInterceptor): + def pre_create_tag_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tag_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tag_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tag_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tag_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tag_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TagBindingsRestTransport(interceptor=MyCustomTagBindingsInterceptor()) + client = TagBindingsClient(transport=transport) + + + """ + def pre_create_tag_binding(self, request: tag_bindings.CreateTagBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_bindings.CreateTagBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tag_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagBindings server. + """ + return request, metadata + + def post_create_tag_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tag_binding + + Override in a subclass to manipulate the response + after it is returned by the TagBindings server but before + it is returned to user code. + """ + return response + def pre_delete_tag_binding(self, request: tag_bindings.DeleteTagBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_bindings.DeleteTagBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tag_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagBindings server. + """ + return request, metadata + + def post_delete_tag_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tag_binding + + Override in a subclass to manipulate the response + after it is returned by the TagBindings server but before + it is returned to user code. + """ + return response + def pre_list_tag_bindings(self, request: tag_bindings.ListTagBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_bindings.ListTagBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tag_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagBindings server. + """ + return request, metadata + + def post_list_tag_bindings(self, response: tag_bindings.ListTagBindingsResponse) -> tag_bindings.ListTagBindingsResponse: + """Post-rpc interceptor for list_tag_bindings + + Override in a subclass to manipulate the response + after it is returned by the TagBindings server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class TagBindingsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TagBindingsRestInterceptor + + +class TagBindingsRestTransport(TagBindingsTransport): + """REST backend transport for TagBindings. + + Allow users to create and manage TagBindings between + TagValues and different cloud resources throughout the GCP + resource hierarchy. + + 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 = 'cloudresourcemanager.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[TagBindingsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TagBindingsRestInterceptor() + 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': '/v3/{name=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="v3") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateTagBinding(TagBindingsRestStub): + def __hash__(self): + return hash("CreateTagBinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_bindings.CreateTagBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create tag binding method over HTTP. + + Args: + request (~.tag_bindings.CreateTagBindingRequest): + The request object. The request message to create a + TagBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/tagBindings', + 'body': 'tag_binding', + }, + ] + request, metadata = self._interceptor.pre_create_tag_binding(request, metadata) + pb_request = tag_bindings.CreateTagBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_tag_binding(resp) + return resp + + class _DeleteTagBinding(TagBindingsRestStub): + def __hash__(self): + return hash("DeleteTagBinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_bindings.DeleteTagBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete tag binding method over HTTP. + + Args: + request (~.tag_bindings.DeleteTagBindingRequest): + The request object. The request message to delete a + TagBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v3/{name=tagBindings/**}', + }, + ] + request, metadata = self._interceptor.pre_delete_tag_binding(request, metadata) + pb_request = tag_bindings.DeleteTagBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_tag_binding(resp) + return resp + + class _ListTagBindings(TagBindingsRestStub): + def __hash__(self): + return hash("ListTagBindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_bindings.ListTagBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tag_bindings.ListTagBindingsResponse: + r"""Call the list tag bindings method over HTTP. + + Args: + request (~.tag_bindings.ListTagBindingsRequest): + The request object. The request message to list all + TagBindings for a parent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tag_bindings.ListTagBindingsResponse: + The ListTagBindings response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/tagBindings', + }, + ] + request, metadata = self._interceptor.pre_list_tag_bindings(request, metadata) + pb_request = tag_bindings.ListTagBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tag_bindings.ListTagBindingsResponse() + pb_resp = tag_bindings.ListTagBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tag_bindings(resp) + return resp + + @property + def create_tag_binding(self) -> Callable[ + [tag_bindings.CreateTagBindingRequest], + 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._CreateTagBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tag_binding(self) -> Callable[ + [tag_bindings.DeleteTagBindingRequest], + 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._DeleteTagBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tag_bindings(self) -> Callable[ + [tag_bindings.ListTagBindingsRequest], + tag_bindings.ListTagBindingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTagBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TagBindingsRestTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py new file mode 100644 index 0000000..e42d5be --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import TagKeysClient +from .async_client import TagKeysAsyncClient + +__all__ = ( + 'TagKeysClient', + 'TagKeysAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py new file mode 100644 index 0000000..b4029ec --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py @@ -0,0 +1,1249 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.tag_keys import pagers +from google.cloud.resourcemanager_v3.types import tag_keys +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TagKeysTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TagKeysGrpcAsyncIOTransport +from .client import TagKeysClient + + +class TagKeysAsyncClient: + """Allow users to create and manage tag keys.""" + + _client: TagKeysClient + + DEFAULT_ENDPOINT = TagKeysClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TagKeysClient.DEFAULT_MTLS_ENDPOINT + + tag_key_path = staticmethod(TagKeysClient.tag_key_path) + parse_tag_key_path = staticmethod(TagKeysClient.parse_tag_key_path) + common_billing_account_path = staticmethod(TagKeysClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TagKeysClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TagKeysClient.common_folder_path) + parse_common_folder_path = staticmethod(TagKeysClient.parse_common_folder_path) + common_organization_path = staticmethod(TagKeysClient.common_organization_path) + parse_common_organization_path = staticmethod(TagKeysClient.parse_common_organization_path) + common_project_path = staticmethod(TagKeysClient.common_project_path) + parse_common_project_path = staticmethod(TagKeysClient.parse_common_project_path) + common_location_path = staticmethod(TagKeysClient.common_location_path) + parse_common_location_path = staticmethod(TagKeysClient.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: + TagKeysAsyncClient: The constructed client. + """ + return TagKeysClient.from_service_account_info.__func__(TagKeysAsyncClient, 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: + TagKeysAsyncClient: The constructed client. + """ + return TagKeysClient.from_service_account_file.__func__(TagKeysAsyncClient, 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 TagKeysClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TagKeysTransport: + """Returns the transport used by the client instance. + + Returns: + TagKeysTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TagKeysClient).get_transport_class, type(TagKeysClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, TagKeysTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tag keys client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TagKeysTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = TagKeysClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_tag_keys(self, + request: Optional[Union[tag_keys.ListTagKeysRequest, 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.ListTagKeysAsyncPager: + r"""Lists all TagKeys for a parent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_list_tag_keys(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_keys(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagKeysRequest, dict]]): + The request object. The request message for listing all + TagKeys under a parent resource. + parent (:class:`str`): + Required. The resource name of the new TagKey's parent. + Must be of the form ``folders/{folder_id}`` or + ``organizations/{org_id}``. + + 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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysAsyncPager: + The ListTagKeys response message. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_keys.ListTagKeysRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_tag_keys, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListTagKeysAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tag_key(self, + request: Optional[Union[tag_keys.GetTagKeyRequest, 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]] = (), + ) -> tag_keys.TagKey: + r"""Retrieves a TagKey. This method will return + ``PERMISSION_DENIED`` if the key does not exist or the user does + not have permission to view it. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_get_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tag_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.GetTagKeyRequest, dict]]): + The request object. The request message for getting a + TagKey. + name (:class:`str`): + Required. A resource name in the format + ``tagKeys/{id}``, such as ``tagKeys/123``. + + 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.resourcemanager_v3.types.TagKey: + A TagKey, used to group a set of + TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_keys.GetTagKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_tag_key, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_tag_key(self, + request: Optional[Union[tag_keys.CreateTagKeyRequest, dict]] = None, + *, + tag_key: Optional[tag_keys.TagKey] = 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 TagKey. If another request with the + same parameters is sent while the original request is in + process, the second request will receive an error. A + maximum of 300 TagKeys can exist under a parent at any + given time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_create_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.create_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagKeyRequest, dict]]): + The request object. The request message for creating a + TagKey. + tag_key (:class:`google.cloud.resourcemanager_v3.types.TagKey`): + Required. The TagKey to be created. Only fields + ``short_name``, ``description``, and ``parent`` are + considered during the creation request. + + This corresponds to the ``tag_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.resourcemanager_v3.types.TagKey` A + TagKey, used to group a set of TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_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.") + + request = tag_keys.CreateTagKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_key is not None: + request.tag_key = tag_key + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_tag_key, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + tag_keys.TagKey, + metadata_type=tag_keys.CreateTagKeyMetadata, + ) + + # Done; return the response. + return response + + async def update_tag_key(self, + request: Optional[Union[tag_keys.UpdateTagKeyRequest, dict]] = None, + *, + tag_key: Optional[tag_keys.TagKey] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the attributes of the TagKey resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_update_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.update_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest, dict]]): + The request object. The request message for updating a + TagKey. + tag_key (:class:`google.cloud.resourcemanager_v3.types.TagKey`): + Required. The new definition of the TagKey. Only the + ``description`` and ``etag`` fields can be updated by + this request. If the ``etag`` field is not empty, it + must match the ``etag`` field of the existing tag key. + Otherwise, ``FAILED_PRECONDITION`` will be returned. + + This corresponds to the ``tag_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Fields to be updated. The mask may only contain + ``description`` or ``etag``. If omitted entirely, both + ``description`` and ``etag`` are assumed to be + significant. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.resourcemanager_v3.types.TagKey` A + TagKey, used to group a set of TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_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.") + + request = tag_keys.UpdateTagKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_key is not None: + request.tag_key = tag_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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_tag_key, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_key.name", request.tag_key.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + tag_keys.TagKey, + metadata_type=tag_keys.UpdateTagKeyMetadata, + ) + + # Done; return the response. + return response + + async def delete_tag_key(self, + request: Optional[Union[tag_keys.DeleteTagKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a TagKey. The TagKey cannot be deleted if it + has any child TagValues. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_delete_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagKeyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest, dict]]): + The request object. The request message for deleting a + TagKey. + name (:class:`str`): + Required. The resource name of a TagKey to be deleted in + the format ``tagKeys/123``. The TagKey cannot be a + parent of any existing TagValues or it will not be + deleted successfully. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.resourcemanager_v3.types.TagKey` A + TagKey, used to group a set of TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_keys.DeleteTagKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_tag_key, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + tag_keys.TagKey, + metadata_type=tag_keys.DeleteTagKeyMetadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for a TagKey. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". The caller must have + ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` + permission on the specified TagKey. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on a TagKey, replacing any + existing policy. The ``resource`` field should be the TagKey's + resource name. For example, "tagKeys/1234". The caller must have + ``resourcemanager.tagKeys.setIamPolicy`` permission on the + identified tagValue. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagKey. + The ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._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), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "TagKeysAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py new file mode 100644 index 0000000..7c8e97d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py @@ -0,0 +1,1434 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.tag_keys import pagers +from google.cloud.resourcemanager_v3.types import tag_keys +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TagKeysTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TagKeysGrpcTransport +from .transports.grpc_asyncio import TagKeysGrpcAsyncIOTransport +from .transports.rest import TagKeysRestTransport + + +class TagKeysClientMeta(type): + """Metaclass for the TagKeys 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[TagKeysTransport]] + _transport_registry["grpc"] = TagKeysGrpcTransport + _transport_registry["grpc_asyncio"] = TagKeysGrpcAsyncIOTransport + _transport_registry["rest"] = TagKeysRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TagKeysTransport]: + """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 TagKeysClient(metaclass=TagKeysClientMeta): + """Allow users to create and manage tag keys.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TagKeysClient: 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: + TagKeysClient: 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) -> TagKeysTransport: + """Returns the transport used by the client instance. + + Returns: + TagKeysTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def tag_key_path(tag_key: str,) -> str: + """Returns a fully-qualified tag_key string.""" + return "tagKeys/{tag_key}".format(tag_key=tag_key, ) + + @staticmethod + def parse_tag_key_path(path: str) -> Dict[str,str]: + """Parses a tag_key path into its component segments.""" + m = re.match(r"^tagKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TagKeysTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tag keys client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TagKeysTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TagKeysTransport): + # transport is a TagKeysTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_tag_keys(self, + request: Optional[Union[tag_keys.ListTagKeysRequest, 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.ListTagKeysPager: + r"""Lists all TagKeys for a parent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_list_tag_keys(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_keys(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.ListTagKeysRequest, dict]): + The request object. The request message for listing all + TagKeys under a parent resource. + parent (str): + Required. The resource name of the new TagKey's parent. + Must be of the form ``folders/{folder_id}`` or + ``organizations/{org_id}``. + + 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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysPager: + The ListTagKeys response message. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_keys.ListTagKeysRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_keys.ListTagKeysRequest): + request = tag_keys.ListTagKeysRequest(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_tag_keys] + + # 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.ListTagKeysPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tag_key(self, + request: Optional[Union[tag_keys.GetTagKeyRequest, 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]] = (), + ) -> tag_keys.TagKey: + r"""Retrieves a TagKey. This method will return + ``PERMISSION_DENIED`` if the key does not exist or the user does + not have permission to view it. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_get_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_tag_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.GetTagKeyRequest, dict]): + The request object. The request message for getting a + TagKey. + name (str): + Required. A resource name in the format + ``tagKeys/{id}``, such as ``tagKeys/123``. + + 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.resourcemanager_v3.types.TagKey: + A TagKey, used to group a set of + TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_keys.GetTagKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_keys.GetTagKeyRequest): + request = tag_keys.GetTagKeyRequest(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_tag_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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_tag_key(self, + request: Optional[Union[tag_keys.CreateTagKeyRequest, dict]] = None, + *, + tag_key: Optional[tag_keys.TagKey] = 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 TagKey. If another request with the + same parameters is sent while the original request is in + process, the second request will receive an error. A + maximum of 300 TagKeys can exist under a parent at any + given time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_create_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.create_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.CreateTagKeyRequest, dict]): + The request object. The request message for creating a + TagKey. + tag_key (google.cloud.resourcemanager_v3.types.TagKey): + Required. The TagKey to be created. Only fields + ``short_name``, ``description``, and ``parent`` are + considered during the creation request. + + This corresponds to the ``tag_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.resourcemanager_v3.types.TagKey` A + TagKey, used to group a set of TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_keys.CreateTagKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_keys.CreateTagKeyRequest): + request = tag_keys.CreateTagKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_key is not None: + request.tag_key = tag_key + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_key] + + # 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, + tag_keys.TagKey, + metadata_type=tag_keys.CreateTagKeyMetadata, + ) + + # Done; return the response. + return response + + def update_tag_key(self, + request: Optional[Union[tag_keys.UpdateTagKeyRequest, dict]] = None, + *, + tag_key: Optional[tag_keys.TagKey] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the attributes of the TagKey resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_update_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.update_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest, dict]): + The request object. The request message for updating a + TagKey. + tag_key (google.cloud.resourcemanager_v3.types.TagKey): + Required. The new definition of the TagKey. Only the + ``description`` and ``etag`` fields can be updated by + this request. If the ``etag`` field is not empty, it + must match the ``etag`` field of the existing tag key. + Otherwise, ``FAILED_PRECONDITION`` will be returned. + + This corresponds to the ``tag_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Fields to be updated. The mask may only contain + ``description`` or ``etag``. If omitted entirely, both + ``description`` and ``etag`` are assumed to be + significant. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.resourcemanager_v3.types.TagKey` A + TagKey, used to group a set of TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_keys.UpdateTagKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_keys.UpdateTagKeyRequest): + request = tag_keys.UpdateTagKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_key is not None: + request.tag_key = tag_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_tag_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_key.name", request.tag_key.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + tag_keys.TagKey, + metadata_type=tag_keys.UpdateTagKeyMetadata, + ) + + # Done; return the response. + return response + + def delete_tag_key(self, + request: Optional[Union[tag_keys.DeleteTagKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a TagKey. The TagKey cannot be deleted if it + has any child TagValues. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_delete_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagKeyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest, dict]): + The request object. The request message for deleting a + TagKey. + name (str): + Required. The resource name of a TagKey to be deleted in + the format ``tagKeys/123``. The TagKey cannot be a + parent of any existing TagValues or it will not be + deleted successfully. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.resourcemanager_v3.types.TagKey` A + TagKey, used to group a set of TagValues. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_keys.DeleteTagKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_keys.DeleteTagKeyRequest): + request = tag_keys.DeleteTagKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_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), + )), + ) + + # 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, + tag_keys.TagKey, + metadata_type=tag_keys.DeleteTagKeyMetadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for a TagKey. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". The caller must have + ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` + permission on the specified TagKey. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on a TagKey, replacing any + existing policy. The ``resource`` field should be the TagKey's + resource name. For example, "tagKeys/1234". The caller must have + ``resourcemanager.tagKeys.setIamPolicy`` permission on the + identified tagValue. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagKey. + The ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "TagKeysClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "TagKeysClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py new file mode 100644 index 0000000..ca6a02c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.resourcemanager_v3.types import tag_keys + + +class ListTagKeysPager: + """A pager for iterating through ``list_tag_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tag_keys`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTagKeys`` requests and continue to iterate + through the ``tag_keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` + 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[..., tag_keys.ListTagKeysResponse], + request: tag_keys.ListTagKeysRequest, + response: tag_keys.ListTagKeysResponse, + *, + 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.resourcemanager_v3.types.ListTagKeysRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListTagKeysResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tag_keys.ListTagKeysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tag_keys.ListTagKeysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tag_keys.TagKey]: + for page in self.pages: + yield from page.tag_keys + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagKeysAsyncPager: + """A pager for iterating through ``list_tag_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tag_keys`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTagKeys`` requests and continue to iterate + through the ``tag_keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` + 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[tag_keys.ListTagKeysResponse]], + request: tag_keys.ListTagKeysRequest, + response: tag_keys.ListTagKeysResponse, + *, + 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.resourcemanager_v3.types.ListTagKeysRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListTagKeysResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tag_keys.ListTagKeysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tag_keys.ListTagKeysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[tag_keys.TagKey]: + async def async_generator(): + async for page in self.pages: + for response in page.tag_keys: + 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/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py new file mode 100644 index 0000000..70f0ce8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import TagKeysTransport +from .grpc import TagKeysGrpcTransport +from .grpc_asyncio import TagKeysGrpcAsyncIOTransport +from .rest import TagKeysRestTransport +from .rest import TagKeysRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TagKeysTransport]] +_transport_registry['grpc'] = TagKeysGrpcTransport +_transport_registry['grpc_asyncio'] = TagKeysGrpcAsyncIOTransport +_transport_registry['rest'] = TagKeysRestTransport + +__all__ = ( + 'TagKeysTransport', + 'TagKeysGrpcTransport', + 'TagKeysGrpcAsyncIOTransport', + 'TagKeysRestTransport', + 'TagKeysRestInterceptor', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py new file mode 100644 index 0000000..be1a3bb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 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.resourcemanager_v3.types import tag_keys +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 TagKeysTransport(abc.ABC): + """Abstract transport class for TagKeys.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_tag_keys: gapic_v1.method.wrap_method( + self.list_tag_keys, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_tag_key: gapic_v1.method.wrap_method( + self.get_tag_key, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_tag_key: gapic_v1.method.wrap_method( + self.create_tag_key, + default_timeout=60.0, + client_info=client_info, + ), + self.update_tag_key: gapic_v1.method.wrap_method( + self.update_tag_key, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_tag_key: gapic_v1.method.wrap_method( + self.delete_tag_key, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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 list_tag_keys(self) -> Callable[ + [tag_keys.ListTagKeysRequest], + Union[ + tag_keys.ListTagKeysResponse, + Awaitable[tag_keys.ListTagKeysResponse] + ]]: + raise NotImplementedError() + + @property + def get_tag_key(self) -> Callable[ + [tag_keys.GetTagKeyRequest], + Union[ + tag_keys.TagKey, + Awaitable[tag_keys.TagKey] + ]]: + raise NotImplementedError() + + @property + def create_tag_key(self) -> Callable[ + [tag_keys.CreateTagKeyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_tag_key(self) -> Callable[ + [tag_keys.UpdateTagKeyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_tag_key(self) -> Callable[ + [tag_keys.DeleteTagKeyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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__ = ( + 'TagKeysTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py new file mode 100644 index 0000000..3bce1f6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py @@ -0,0 +1,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3.types import tag_keys +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 TagKeysTransport, DEFAULT_CLIENT_INFO + + +class TagKeysGrpcTransport(TagKeysTransport): + """gRPC backend transport for TagKeys. + + Allow users to create and manage tag keys. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudresourcemanager.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 list_tag_keys(self) -> Callable[ + [tag_keys.ListTagKeysRequest], + tag_keys.ListTagKeysResponse]: + r"""Return a callable for the list tag keys method over gRPC. + + Lists all TagKeys for a parent resource. + + Returns: + Callable[[~.ListTagKeysRequest], + ~.ListTagKeysResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_keys' not in self._stubs: + self._stubs['list_tag_keys'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/ListTagKeys', + request_serializer=tag_keys.ListTagKeysRequest.serialize, + response_deserializer=tag_keys.ListTagKeysResponse.deserialize, + ) + return self._stubs['list_tag_keys'] + + @property + def get_tag_key(self) -> Callable[ + [tag_keys.GetTagKeyRequest], + tag_keys.TagKey]: + r"""Return a callable for the get tag key method over gRPC. + + Retrieves a TagKey. This method will return + ``PERMISSION_DENIED`` if the key does not exist or the user does + not have permission to view it. + + Returns: + Callable[[~.GetTagKeyRequest], + ~.TagKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_tag_key' not in self._stubs: + self._stubs['get_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/GetTagKey', + request_serializer=tag_keys.GetTagKeyRequest.serialize, + response_deserializer=tag_keys.TagKey.deserialize, + ) + return self._stubs['get_tag_key'] + + @property + def create_tag_key(self) -> Callable[ + [tag_keys.CreateTagKeyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create tag key method over gRPC. + + Creates a new TagKey. If another request with the + same parameters is sent while the original request is in + process, the second request will receive an error. A + maximum of 300 TagKeys can exist under a parent at any + given time. + + Returns: + Callable[[~.CreateTagKeyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_key' not in self._stubs: + self._stubs['create_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/CreateTagKey', + request_serializer=tag_keys.CreateTagKeyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tag_key'] + + @property + def update_tag_key(self) -> Callable[ + [tag_keys.UpdateTagKeyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update tag key method over gRPC. + + Updates the attributes of the TagKey resource. + + Returns: + Callable[[~.UpdateTagKeyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_key' not in self._stubs: + self._stubs['update_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/UpdateTagKey', + request_serializer=tag_keys.UpdateTagKeyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tag_key'] + + @property + def delete_tag_key(self) -> Callable[ + [tag_keys.DeleteTagKeyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete tag key method over gRPC. + + Deletes a TagKey. The TagKey cannot be deleted if it + has any child TagValues. + + Returns: + Callable[[~.DeleteTagKeyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_tag_key' not in self._stubs: + self._stubs['delete_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/DeleteTagKey', + request_serializer=tag_keys.DeleteTagKeyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tag_key'] + + @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 access control policy for a TagKey. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". The caller must have + ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` + permission on the specified TagKey. + + 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.cloud.resourcemanager.v3.TagKeys/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on a TagKey, replacing any + existing policy. The ``resource`` field should be the TagKey's + resource name. For example, "tagKeys/1234". The caller must have + ``resourcemanager.tagKeys.setIamPolicy`` permission on the + identified tagValue. + + 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.cloud.resourcemanager.v3.TagKeys/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the specified TagKey. + The ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.TagKeys/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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TagKeysGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py new file mode 100644 index 0000000..20b7bdf --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.resourcemanager_v3.types import tag_keys +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 TagKeysTransport, DEFAULT_CLIENT_INFO +from .grpc import TagKeysGrpcTransport + + +class TagKeysGrpcAsyncIOTransport(TagKeysTransport): + """gRPC AsyncIO backend transport for TagKeys. + + Allow users to create and manage tag keys. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_tag_keys(self) -> Callable[ + [tag_keys.ListTagKeysRequest], + Awaitable[tag_keys.ListTagKeysResponse]]: + r"""Return a callable for the list tag keys method over gRPC. + + Lists all TagKeys for a parent resource. + + Returns: + Callable[[~.ListTagKeysRequest], + Awaitable[~.ListTagKeysResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_keys' not in self._stubs: + self._stubs['list_tag_keys'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/ListTagKeys', + request_serializer=tag_keys.ListTagKeysRequest.serialize, + response_deserializer=tag_keys.ListTagKeysResponse.deserialize, + ) + return self._stubs['list_tag_keys'] + + @property + def get_tag_key(self) -> Callable[ + [tag_keys.GetTagKeyRequest], + Awaitable[tag_keys.TagKey]]: + r"""Return a callable for the get tag key method over gRPC. + + Retrieves a TagKey. This method will return + ``PERMISSION_DENIED`` if the key does not exist or the user does + not have permission to view it. + + Returns: + Callable[[~.GetTagKeyRequest], + Awaitable[~.TagKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_tag_key' not in self._stubs: + self._stubs['get_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/GetTagKey', + request_serializer=tag_keys.GetTagKeyRequest.serialize, + response_deserializer=tag_keys.TagKey.deserialize, + ) + return self._stubs['get_tag_key'] + + @property + def create_tag_key(self) -> Callable[ + [tag_keys.CreateTagKeyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create tag key method over gRPC. + + Creates a new TagKey. If another request with the + same parameters is sent while the original request is in + process, the second request will receive an error. A + maximum of 300 TagKeys can exist under a parent at any + given time. + + Returns: + Callable[[~.CreateTagKeyRequest], + 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_tag_key' not in self._stubs: + self._stubs['create_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/CreateTagKey', + request_serializer=tag_keys.CreateTagKeyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tag_key'] + + @property + def update_tag_key(self) -> Callable[ + [tag_keys.UpdateTagKeyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update tag key method over gRPC. + + Updates the attributes of the TagKey resource. + + Returns: + Callable[[~.UpdateTagKeyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_tag_key' not in self._stubs: + self._stubs['update_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/UpdateTagKey', + request_serializer=tag_keys.UpdateTagKeyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tag_key'] + + @property + def delete_tag_key(self) -> Callable[ + [tag_keys.DeleteTagKeyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete tag key method over gRPC. + + Deletes a TagKey. The TagKey cannot be deleted if it + has any child TagValues. + + Returns: + Callable[[~.DeleteTagKeyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_tag_key' not in self._stubs: + self._stubs['delete_tag_key'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagKeys/DeleteTagKey', + request_serializer=tag_keys.DeleteTagKeyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tag_key'] + + @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 access control policy for a TagKey. The returned policy + may be empty if no such policy or resource exists. The + ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". The caller must have + ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` + permission on the specified TagKey. + + 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.cloud.resourcemanager.v3.TagKeys/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on a TagKey, replacing any + existing policy. The ``resource`` field should be the TagKey's + resource name. For example, "tagKeys/1234". The caller must have + ``resourcemanager.tagKeys.setIamPolicy`` permission on the + identified tagValue. + + 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.cloud.resourcemanager.v3.TagKeys/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the specified TagKey. + The ``resource`` field should be the TagKey's resource name. For + example, "tagKeys/1234". + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.TagKeys/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'TagKeysGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py new file mode 100644 index 0000000..27013fc --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py @@ -0,0 +1,1299 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.resourcemanager_v3.types import tag_keys +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 TagKeysTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class TagKeysRestInterceptor: + """Interceptor for TagKeys. + + 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 TagKeysRestTransport. + + .. code-block:: python + class MyCustomTagKeysInterceptor(TagKeysRestInterceptor): + def pre_create_tag_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tag_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tag_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tag_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tag_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tag_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tag_keys(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tag_keys(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tag_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tag_key(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TagKeysRestTransport(interceptor=MyCustomTagKeysInterceptor()) + client = TagKeysClient(transport=transport) + + + """ + def pre_create_tag_key(self, request: tag_keys.CreateTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.CreateTagKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tag_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagKeys server. + """ + return request, metadata + + def post_create_tag_key(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tag_key + + Override in a subclass to manipulate the response + after it is returned by the TagKeys server but before + it is returned to user code. + """ + return response + def pre_delete_tag_key(self, request: tag_keys.DeleteTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.DeleteTagKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tag_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagKeys server. + """ + return request, metadata + + def post_delete_tag_key(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tag_key + + Override in a subclass to manipulate the response + after it is returned by the TagKeys 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 TagKeys 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 TagKeys server but before + it is returned to user code. + """ + return response + def pre_get_tag_key(self, request: tag_keys.GetTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.GetTagKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_tag_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagKeys server. + """ + return request, metadata + + def post_get_tag_key(self, response: tag_keys.TagKey) -> tag_keys.TagKey: + """Post-rpc interceptor for get_tag_key + + Override in a subclass to manipulate the response + after it is returned by the TagKeys server but before + it is returned to user code. + """ + return response + def pre_list_tag_keys(self, request: tag_keys.ListTagKeysRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.ListTagKeysRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tag_keys + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagKeys server. + """ + return request, metadata + + def post_list_tag_keys(self, response: tag_keys.ListTagKeysResponse) -> tag_keys.ListTagKeysResponse: + """Post-rpc interceptor for list_tag_keys + + Override in a subclass to manipulate the response + after it is returned by the TagKeys 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 TagKeys 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 TagKeys 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 TagKeys 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 TagKeys server but before + it is returned to user code. + """ + return response + def pre_update_tag_key(self, request: tag_keys.UpdateTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.UpdateTagKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_tag_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagKeys server. + """ + return request, metadata + + def post_update_tag_key(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_tag_key + + Override in a subclass to manipulate the response + after it is returned by the TagKeys server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class TagKeysRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TagKeysRestInterceptor + + +class TagKeysRestTransport(TagKeysTransport): + """REST backend transport for TagKeys. + + Allow users to create and manage tag keys. + + 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 = 'cloudresourcemanager.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[TagKeysRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TagKeysRestInterceptor() + 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': '/v3/{name=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="v3") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateTagKey(TagKeysRestStub): + def __hash__(self): + return hash("CreateTagKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_keys.CreateTagKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create tag key method over HTTP. + + Args: + request (~.tag_keys.CreateTagKeyRequest): + The request object. The request message for creating a + TagKey. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/tagKeys', + 'body': 'tag_key', + }, + ] + request, metadata = self._interceptor.pre_create_tag_key(request, metadata) + pb_request = tag_keys.CreateTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_tag_key(resp) + return resp + + class _DeleteTagKey(TagKeysRestStub): + def __hash__(self): + return hash("DeleteTagKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_keys.DeleteTagKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete tag key method over HTTP. + + Args: + request (~.tag_keys.DeleteTagKeyRequest): + The request object. The request message for deleting a + TagKey. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v3/{name=tagKeys/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_tag_key(request, metadata) + pb_request = tag_keys.DeleteTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_tag_key(resp) + return resp + + class _GetIamPolicy(TagKeysRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=tagKeys/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetTagKey(TagKeysRestStub): + def __hash__(self): + return hash("GetTagKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_keys.GetTagKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tag_keys.TagKey: + r"""Call the get tag key method over HTTP. + + Args: + request (~.tag_keys.GetTagKeyRequest): + The request object. The request message for getting a + TagKey. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tag_keys.TagKey: + A TagKey, used to group a set of + TagValues. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/{name=tagKeys/*}', + }, + ] + request, metadata = self._interceptor.pre_get_tag_key(request, metadata) + pb_request = tag_keys.GetTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tag_keys.TagKey() + pb_resp = tag_keys.TagKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_tag_key(resp) + return resp + + class _ListTagKeys(TagKeysRestStub): + def __hash__(self): + return hash("ListTagKeys") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_keys.ListTagKeysRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tag_keys.ListTagKeysResponse: + r"""Call the list tag keys method over HTTP. + + Args: + request (~.tag_keys.ListTagKeysRequest): + The request object. The request message for listing all + TagKeys under a parent resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tag_keys.ListTagKeysResponse: + The ListTagKeys response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/tagKeys', + }, + ] + request, metadata = self._interceptor.pre_list_tag_keys(request, metadata) + pb_request = tag_keys.ListTagKeysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tag_keys.ListTagKeysResponse() + pb_resp = tag_keys.ListTagKeysResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tag_keys(resp) + return resp + + class _SetIamPolicy(TagKeysRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=tagKeys/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(TagKeysRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=tagKeys/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateTagKey(TagKeysRestStub): + def __hash__(self): + return hash("UpdateTagKey") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_keys.UpdateTagKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update tag key method over HTTP. + + Args: + request (~.tag_keys.UpdateTagKeyRequest): + The request object. The request message for updating a + TagKey. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v3/{tag_key.name=tagKeys/*}', + 'body': 'tag_key', + }, + ] + request, metadata = self._interceptor.pre_update_tag_key(request, metadata) + pb_request = tag_keys.UpdateTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_tag_key(resp) + return resp + + @property + def create_tag_key(self) -> Callable[ + [tag_keys.CreateTagKeyRequest], + 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._CreateTagKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tag_key(self) -> Callable[ + [tag_keys.DeleteTagKeyRequest], + 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._DeleteTagKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tag_key(self) -> Callable[ + [tag_keys.GetTagKeyRequest], + tag_keys.TagKey]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTagKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tag_keys(self) -> Callable[ + [tag_keys.ListTagKeysRequest], + tag_keys.ListTagKeysResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTagKeys(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tag_key(self) -> Callable[ + [tag_keys.UpdateTagKeyRequest], + 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._UpdateTagKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TagKeysRestTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py new file mode 100644 index 0000000..e1300af --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import TagValuesClient +from .async_client import TagValuesAsyncClient + +__all__ = ( + 'TagValuesClient', + 'TagValuesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py new file mode 100644 index 0000000..e0822b4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py @@ -0,0 +1,1247 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.tag_values import pagers +from google.cloud.resourcemanager_v3.types import tag_values +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TagValuesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TagValuesGrpcAsyncIOTransport +from .client import TagValuesClient + + +class TagValuesAsyncClient: + """Allow users to create and manage tag values.""" + + _client: TagValuesClient + + DEFAULT_ENDPOINT = TagValuesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TagValuesClient.DEFAULT_MTLS_ENDPOINT + + tag_value_path = staticmethod(TagValuesClient.tag_value_path) + parse_tag_value_path = staticmethod(TagValuesClient.parse_tag_value_path) + common_billing_account_path = staticmethod(TagValuesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TagValuesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TagValuesClient.common_folder_path) + parse_common_folder_path = staticmethod(TagValuesClient.parse_common_folder_path) + common_organization_path = staticmethod(TagValuesClient.common_organization_path) + parse_common_organization_path = staticmethod(TagValuesClient.parse_common_organization_path) + common_project_path = staticmethod(TagValuesClient.common_project_path) + parse_common_project_path = staticmethod(TagValuesClient.parse_common_project_path) + common_location_path = staticmethod(TagValuesClient.common_location_path) + parse_common_location_path = staticmethod(TagValuesClient.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: + TagValuesAsyncClient: The constructed client. + """ + return TagValuesClient.from_service_account_info.__func__(TagValuesAsyncClient, 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: + TagValuesAsyncClient: The constructed client. + """ + return TagValuesClient.from_service_account_file.__func__(TagValuesAsyncClient, 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 TagValuesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TagValuesTransport: + """Returns the transport used by the client instance. + + Returns: + TagValuesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TagValuesClient).get_transport_class, type(TagValuesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, TagValuesTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tag values client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TagValuesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = TagValuesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_tag_values(self, + request: Optional[Union[tag_values.ListTagValuesRequest, 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.ListTagValuesAsyncPager: + r"""Lists all TagValues for a specific TagKey. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_list_tag_values(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagValuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_values(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagValuesRequest, dict]]): + The request object. The request message for listing + TagValues for the specified TagKey. + parent (:class:`str`): + Required. Resource name for TagKey, parent of the + TagValues to be listed, in the format ``tagKeys/123``. + + 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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesAsyncPager: + The ListTagValues response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_values.ListTagValuesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_tag_values, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListTagValuesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tag_value(self, + request: Optional[Union[tag_values.GetTagValueRequest, 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]] = (), + ) -> tag_values.TagValue: + r"""Retrieves TagValue. If the TagValue or namespaced name does not + exist, or if the user does not have permission to view it, this + method will return ``PERMISSION_DENIED``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_get_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagValueRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tag_value(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.GetTagValueRequest, dict]]): + The request object. The request message for getting a + TagValue. + name (:class:`str`): + Required. Resource name for TagValue to be fetched in + the format ``tagValues/456``. + + 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.resourcemanager_v3.types.TagValue: + A TagValue is a child of a particular + TagKey. This is used to group cloud + resources for the purpose of controlling + them using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_values.GetTagValueRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_tag_value, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_tag_value(self, + request: Optional[Union[tag_values.CreateTagValueRequest, dict]] = None, + *, + tag_value: Optional[tag_values.TagValue] = 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 TagValue as a child of the specified + TagKey. If a another request with the same parameters is + sent while the original request is in process the second + request will receive an error. A maximum of 300 + TagValues can exist under a TagKey at any given time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_create_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.create_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagValueRequest, dict]]): + The request object. The request message for creating a + TagValue. + tag_value (:class:`google.cloud.resourcemanager_v3.types.TagValue`): + Required. The TagValue to be created. Only fields + ``short_name``, ``description``, and ``parent`` are + considered during the creation request. + + This corresponds to the ``tag_value`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group + cloud resources for the purpose of controlling them + using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_value]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_values.CreateTagValueRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_value is not None: + request.tag_value = tag_value + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_tag_value, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + tag_values.TagValue, + metadata_type=tag_values.CreateTagValueMetadata, + ) + + # Done; return the response. + return response + + async def update_tag_value(self, + request: Optional[Union[tag_values.UpdateTagValueRequest, dict]] = None, + *, + tag_value: Optional[tag_values.TagValue] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the attributes of the TagValue resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_update_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.update_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateTagValueRequest, dict]]): + The request object. The request message for updating a + TagValue. + tag_value (:class:`google.cloud.resourcemanager_v3.types.TagValue`): + Required. The new definition of the TagValue. Only + fields ``description`` and ``etag`` fields can be + updated by this request. If the ``etag`` field is + nonempty, it must match the ``etag`` field of the + existing ControlGroup. Otherwise, + ``FAILED_PRECONDITION`` will be returned. + + This corresponds to the ``tag_value`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group + cloud resources for the purpose of controlling them + using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_value, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_values.UpdateTagValueRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_value is not None: + request.tag_value = tag_value + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_tag_value, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_value.name", request.tag_value.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + tag_values.TagValue, + metadata_type=tag_values.UpdateTagValueMetadata, + ) + + # Done; return the response. + return response + + async def delete_tag_value(self, + request: Optional[Union[tag_values.DeleteTagValueRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a TagValue. The TagValue cannot have any + bindings when it is deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + async def sample_delete_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagValueRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagValueRequest, dict]]): + The request object. The request message for deleting a + TagValue. + name (:class:`str`): + Required. Resource name for TagValue + to be deleted in the format + tagValues/456. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group + cloud resources for the purpose of controlling them + using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = tag_values.DeleteTagValueRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_tag_value, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + tag_values.TagValue, + metadata_type=tag_values.DeleteTagValueMetadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for a TagValue. The returned + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the TagValue's resource name. For + example: ``tagValues/1234``. The caller must have the + ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` + permission on the identified TagValue to get the access control + policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on a TagValue, replacing any + existing policy. The ``resource`` field should be the TagValue's + resource name. For example: ``tagValues/1234``. The caller must + have ``resourcemanager.tagValues.setIamPolicy`` permission on + the identified tagValue. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagValue. + The ``resource`` field should be the TagValue's resource name. + For example: ``tagValues/1234``. + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._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), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "TagValuesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py new file mode 100644 index 0000000..2d19968 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py @@ -0,0 +1,1432 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.resourcemanager_v3 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.resourcemanager_v3.services.tag_values import pagers +from google.cloud.resourcemanager_v3.types import tag_values +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TagValuesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TagValuesGrpcTransport +from .transports.grpc_asyncio import TagValuesGrpcAsyncIOTransport +from .transports.rest import TagValuesRestTransport + + +class TagValuesClientMeta(type): + """Metaclass for the TagValues 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[TagValuesTransport]] + _transport_registry["grpc"] = TagValuesGrpcTransport + _transport_registry["grpc_asyncio"] = TagValuesGrpcAsyncIOTransport + _transport_registry["rest"] = TagValuesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TagValuesTransport]: + """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 TagValuesClient(metaclass=TagValuesClientMeta): + """Allow users to create and manage tag values.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TagValuesClient: 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: + TagValuesClient: 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) -> TagValuesTransport: + """Returns the transport used by the client instance. + + Returns: + TagValuesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def tag_value_path(tag_value: str,) -> str: + """Returns a fully-qualified tag_value string.""" + return "tagValues/{tag_value}".format(tag_value=tag_value, ) + + @staticmethod + def parse_tag_value_path(path: str) -> Dict[str,str]: + """Parses a tag_value path into its component segments.""" + m = re.match(r"^tagValues/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TagValuesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tag values client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TagValuesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TagValuesTransport): + # transport is a TagValuesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_tag_values(self, + request: Optional[Union[tag_values.ListTagValuesRequest, 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.ListTagValuesPager: + r"""Lists all TagValues for a specific TagKey. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_list_tag_values(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagValuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_values(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.ListTagValuesRequest, dict]): + The request object. The request message for listing + TagValues for the specified TagKey. + parent (str): + Required. Resource name for TagKey, parent of the + TagValues to be listed, in the format ``tagKeys/123``. + + 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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesPager: + The ListTagValues response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_values.ListTagValuesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_values.ListTagValuesRequest): + request = tag_values.ListTagValuesRequest(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_tag_values] + + # 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.ListTagValuesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tag_value(self, + request: Optional[Union[tag_values.GetTagValueRequest, 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]] = (), + ) -> tag_values.TagValue: + r"""Retrieves TagValue. If the TagValue or namespaced name does not + exist, or if the user does not have permission to view it, this + method will return ``PERMISSION_DENIED``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_get_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagValueRequest( + name="name_value", + ) + + # Make the request + response = client.get_tag_value(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.GetTagValueRequest, dict]): + The request object. The request message for getting a + TagValue. + name (str): + Required. Resource name for TagValue to be fetched in + the format ``tagValues/456``. + + 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.resourcemanager_v3.types.TagValue: + A TagValue is a child of a particular + TagKey. This is used to group cloud + resources for the purpose of controlling + them using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_values.GetTagValueRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_values.GetTagValueRequest): + request = tag_values.GetTagValueRequest(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_tag_value] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_tag_value(self, + request: Optional[Union[tag_values.CreateTagValueRequest, dict]] = None, + *, + tag_value: Optional[tag_values.TagValue] = 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 TagValue as a child of the specified + TagKey. If a another request with the same parameters is + sent while the original request is in process the second + request will receive an error. A maximum of 300 + TagValues can exist under a TagKey at any given time. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_create_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.create_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.CreateTagValueRequest, dict]): + The request object. The request message for creating a + TagValue. + tag_value (google.cloud.resourcemanager_v3.types.TagValue): + Required. The TagValue to be created. Only fields + ``short_name``, ``description``, and ``parent`` are + considered during the creation request. + + This corresponds to the ``tag_value`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group + cloud resources for the purpose of controlling them + using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_value]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_values.CreateTagValueRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_values.CreateTagValueRequest): + request = tag_values.CreateTagValueRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_value is not None: + request.tag_value = tag_value + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tag_value] + + # 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, + tag_values.TagValue, + metadata_type=tag_values.CreateTagValueMetadata, + ) + + # Done; return the response. + return response + + def update_tag_value(self, + request: Optional[Union[tag_values.UpdateTagValueRequest, dict]] = None, + *, + tag_value: Optional[tag_values.TagValue] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the attributes of the TagValue resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_update_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.update_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.UpdateTagValueRequest, dict]): + The request object. The request message for updating a + TagValue. + tag_value (google.cloud.resourcemanager_v3.types.TagValue): + Required. The new definition of the TagValue. Only + fields ``description`` and ``etag`` fields can be + updated by this request. If the ``etag`` field is + nonempty, it must match the ``etag`` field of the + existing ControlGroup. Otherwise, + ``FAILED_PRECONDITION`` will be returned. + + This corresponds to the ``tag_value`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group + cloud resources for the purpose of controlling them + using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([tag_value, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_values.UpdateTagValueRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_values.UpdateTagValueRequest): + request = tag_values.UpdateTagValueRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tag_value is not None: + request.tag_value = tag_value + 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_tag_value] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("tag_value.name", request.tag_value.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + tag_values.TagValue, + metadata_type=tag_values.UpdateTagValueMetadata, + ) + + # Done; return the response. + return response + + def delete_tag_value(self, + request: Optional[Union[tag_values.DeleteTagValueRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a TagValue. The TagValue cannot have any + bindings when it is deleted. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + + def sample_delete_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagValueRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.resourcemanager_v3.types.DeleteTagValueRequest, dict]): + The request object. The request message for deleting a + TagValue. + name (str): + Required. Resource name for TagValue + to be deleted in the format + tagValues/456. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group + cloud resources for the purpose of controlling them + using policies. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a tag_values.DeleteTagValueRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, tag_values.DeleteTagValueRequest): + request = tag_values.DeleteTagValueRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tag_value] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + tag_values.TagValue, + metadata_type=tag_values.DeleteTagValueMetadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy for a TagValue. The returned + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the TagValue's resource name. For + example: ``tagValues/1234``. The caller must have the + ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` + permission on the identified TagValue to get the access control + policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = 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 access control policy on a TagValue, replacing any + existing policy. The ``resource`` field should be the TagValue's + resource name. For example: ``tagValues/1234``. The caller must + have ``resourcemanager.tagValues.setIamPolicy`` permission on + the identified tagValue. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **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')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **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') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagValue. + The ``resource`` field should be the TagValue's resource name. + For example: ``tagValues/1234``. + + There are no permissions required for making this API call. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import resourcemanager_v3 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "TagValuesClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "TagValuesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py new file mode 100644 index 0000000..9094cf9 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.resourcemanager_v3.types import tag_values + + +class ListTagValuesPager: + """A pager for iterating through ``list_tag_values`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tag_values`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTagValues`` requests and continue to iterate + through the ``tag_values`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` + 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[..., tag_values.ListTagValuesResponse], + request: tag_values.ListTagValuesRequest, + response: tag_values.ListTagValuesResponse, + *, + 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.resourcemanager_v3.types.ListTagValuesRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListTagValuesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tag_values.ListTagValuesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[tag_values.ListTagValuesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[tag_values.TagValue]: + for page in self.pages: + yield from page.tag_values + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTagValuesAsyncPager: + """A pager for iterating through ``list_tag_values`` requests. + + This class thinly wraps an initial + :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tag_values`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTagValues`` requests and continue to iterate + through the ``tag_values`` field on the + corresponding responses. + + All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` + 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[tag_values.ListTagValuesResponse]], + request: tag_values.ListTagValuesRequest, + response: tag_values.ListTagValuesResponse, + *, + 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.resourcemanager_v3.types.ListTagValuesRequest): + The initial request object. + response (google.cloud.resourcemanager_v3.types.ListTagValuesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = tag_values.ListTagValuesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[tag_values.ListTagValuesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[tag_values.TagValue]: + async def async_generator(): + async for page in self.pages: + for response in page.tag_values: + 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/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py new file mode 100644 index 0000000..0eed143 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import TagValuesTransport +from .grpc import TagValuesGrpcTransport +from .grpc_asyncio import TagValuesGrpcAsyncIOTransport +from .rest import TagValuesRestTransport +from .rest import TagValuesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TagValuesTransport]] +_transport_registry['grpc'] = TagValuesGrpcTransport +_transport_registry['grpc_asyncio'] = TagValuesGrpcAsyncIOTransport +_transport_registry['rest'] = TagValuesRestTransport + +__all__ = ( + 'TagValuesTransport', + 'TagValuesGrpcTransport', + 'TagValuesGrpcAsyncIOTransport', + 'TagValuesRestTransport', + 'TagValuesRestInterceptor', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py new file mode 100644 index 0000000..3b8cf01 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3 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.resourcemanager_v3.types import tag_values +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 TagValuesTransport(abc.ABC): + """Abstract transport class for TagValues.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_tag_values: gapic_v1.method.wrap_method( + self.list_tag_values, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_tag_value: gapic_v1.method.wrap_method( + self.get_tag_value, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_tag_value: gapic_v1.method.wrap_method( + self.create_tag_value, + default_timeout=60.0, + client_info=client_info, + ), + self.update_tag_value: gapic_v1.method.wrap_method( + self.update_tag_value, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_tag_value: gapic_v1.method.wrap_method( + self.delete_tag_value, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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 list_tag_values(self) -> Callable[ + [tag_values.ListTagValuesRequest], + Union[ + tag_values.ListTagValuesResponse, + Awaitable[tag_values.ListTagValuesResponse] + ]]: + raise NotImplementedError() + + @property + def get_tag_value(self) -> Callable[ + [tag_values.GetTagValueRequest], + Union[ + tag_values.TagValue, + Awaitable[tag_values.TagValue] + ]]: + raise NotImplementedError() + + @property + def create_tag_value(self) -> Callable[ + [tag_values.CreateTagValueRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_tag_value(self) -> Callable[ + [tag_values.UpdateTagValueRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_tag_value(self) -> Callable[ + [tag_values.DeleteTagValueRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + 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 set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + 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__ = ( + 'TagValuesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py new file mode 100644 index 0000000..252b229 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py @@ -0,0 +1,488 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager_v3.types import tag_values +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 TagValuesTransport, DEFAULT_CLIENT_INFO + + +class TagValuesGrpcTransport(TagValuesTransport): + """gRPC backend transport for TagValues. + + Allow users to create and manage tag values. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudresourcemanager.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 list_tag_values(self) -> Callable[ + [tag_values.ListTagValuesRequest], + tag_values.ListTagValuesResponse]: + r"""Return a callable for the list tag values method over gRPC. + + Lists all TagValues for a specific TagKey. + + Returns: + Callable[[~.ListTagValuesRequest], + ~.ListTagValuesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_values' not in self._stubs: + self._stubs['list_tag_values'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/ListTagValues', + request_serializer=tag_values.ListTagValuesRequest.serialize, + response_deserializer=tag_values.ListTagValuesResponse.deserialize, + ) + return self._stubs['list_tag_values'] + + @property + def get_tag_value(self) -> Callable[ + [tag_values.GetTagValueRequest], + tag_values.TagValue]: + r"""Return a callable for the get tag value method over gRPC. + + Retrieves TagValue. If the TagValue or namespaced name does not + exist, or if the user does not have permission to view it, this + method will return ``PERMISSION_DENIED``. + + Returns: + Callable[[~.GetTagValueRequest], + ~.TagValue]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_tag_value' not in self._stubs: + self._stubs['get_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/GetTagValue', + request_serializer=tag_values.GetTagValueRequest.serialize, + response_deserializer=tag_values.TagValue.deserialize, + ) + return self._stubs['get_tag_value'] + + @property + def create_tag_value(self) -> Callable[ + [tag_values.CreateTagValueRequest], + operations_pb2.Operation]: + r"""Return a callable for the create tag value method over gRPC. + + Creates a TagValue as a child of the specified + TagKey. If a another request with the same parameters is + sent while the original request is in process the second + request will receive an error. A maximum of 300 + TagValues can exist under a TagKey at any given time. + + Returns: + Callable[[~.CreateTagValueRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_value' not in self._stubs: + self._stubs['create_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/CreateTagValue', + request_serializer=tag_values.CreateTagValueRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tag_value'] + + @property + def update_tag_value(self) -> Callable[ + [tag_values.UpdateTagValueRequest], + operations_pb2.Operation]: + r"""Return a callable for the update tag value method over gRPC. + + Updates the attributes of the TagValue resource. + + Returns: + Callable[[~.UpdateTagValueRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_value' not in self._stubs: + self._stubs['update_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/UpdateTagValue', + request_serializer=tag_values.UpdateTagValueRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tag_value'] + + @property + def delete_tag_value(self) -> Callable[ + [tag_values.DeleteTagValueRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete tag value method over gRPC. + + Deletes a TagValue. The TagValue cannot have any + bindings when it is deleted. + + Returns: + Callable[[~.DeleteTagValueRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_tag_value' not in self._stubs: + self._stubs['delete_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/DeleteTagValue', + request_serializer=tag_values.DeleteTagValueRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tag_value'] + + @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 access control policy for a TagValue. The returned + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the TagValue's resource name. For + example: ``tagValues/1234``. The caller must have the + ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` + permission on the identified TagValue to get the access control + policy. + + 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.cloud.resourcemanager.v3.TagValues/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on a TagValue, replacing any + existing policy. The ``resource`` field should be the TagValue's + resource name. For example: ``tagValues/1234``. The caller must + have ``resourcemanager.tagValues.setIamPolicy`` permission on + the identified tagValue. + + 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.cloud.resourcemanager.v3.TagValues/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the specified TagValue. + The ``resource`` field should be the TagValue's resource name. + For example: ``tagValues/1234``. + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.TagValues/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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TagValuesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py new file mode 100644 index 0000000..5f588c8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py @@ -0,0 +1,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.resourcemanager_v3.types import tag_values +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 TagValuesTransport, DEFAULT_CLIENT_INFO +from .grpc import TagValuesGrpcTransport + + +class TagValuesGrpcAsyncIOTransport(TagValuesTransport): + """gRPC AsyncIO backend transport for TagValues. + + Allow users to create and manage tag values. + + 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 = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudresourcemanager.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_tag_values(self) -> Callable[ + [tag_values.ListTagValuesRequest], + Awaitable[tag_values.ListTagValuesResponse]]: + r"""Return a callable for the list tag values method over gRPC. + + Lists all TagValues for a specific TagKey. + + Returns: + Callable[[~.ListTagValuesRequest], + Awaitable[~.ListTagValuesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_tag_values' not in self._stubs: + self._stubs['list_tag_values'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/ListTagValues', + request_serializer=tag_values.ListTagValuesRequest.serialize, + response_deserializer=tag_values.ListTagValuesResponse.deserialize, + ) + return self._stubs['list_tag_values'] + + @property + def get_tag_value(self) -> Callable[ + [tag_values.GetTagValueRequest], + Awaitable[tag_values.TagValue]]: + r"""Return a callable for the get tag value method over gRPC. + + Retrieves TagValue. If the TagValue or namespaced name does not + exist, or if the user does not have permission to view it, this + method will return ``PERMISSION_DENIED``. + + Returns: + Callable[[~.GetTagValueRequest], + Awaitable[~.TagValue]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_tag_value' not in self._stubs: + self._stubs['get_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/GetTagValue', + request_serializer=tag_values.GetTagValueRequest.serialize, + response_deserializer=tag_values.TagValue.deserialize, + ) + return self._stubs['get_tag_value'] + + @property + def create_tag_value(self) -> Callable[ + [tag_values.CreateTagValueRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create tag value method over gRPC. + + Creates a TagValue as a child of the specified + TagKey. If a another request with the same parameters is + sent while the original request is in process the second + request will receive an error. A maximum of 300 + TagValues can exist under a TagKey at any given time. + + Returns: + Callable[[~.CreateTagValueRequest], + 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_tag_value' not in self._stubs: + self._stubs['create_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/CreateTagValue', + request_serializer=tag_values.CreateTagValueRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_tag_value'] + + @property + def update_tag_value(self) -> Callable[ + [tag_values.UpdateTagValueRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update tag value method over gRPC. + + Updates the attributes of the TagValue resource. + + Returns: + Callable[[~.UpdateTagValueRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_tag_value' not in self._stubs: + self._stubs['update_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/UpdateTagValue', + request_serializer=tag_values.UpdateTagValueRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_tag_value'] + + @property + def delete_tag_value(self) -> Callable[ + [tag_values.DeleteTagValueRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete tag value method over gRPC. + + Deletes a TagValue. The TagValue cannot have any + bindings when it is deleted. + + Returns: + Callable[[~.DeleteTagValueRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_tag_value' not in self._stubs: + self._stubs['delete_tag_value'] = self.grpc_channel.unary_unary( + '/google.cloud.resourcemanager.v3.TagValues/DeleteTagValue', + request_serializer=tag_values.DeleteTagValueRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_tag_value'] + + @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 access control policy for a TagValue. The returned + policy may be empty if no such policy or resource exists. The + ``resource`` field should be the TagValue's resource name. For + example: ``tagValues/1234``. The caller must have the + ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` + permission on the identified TagValue to get the access control + policy. + + 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.cloud.resourcemanager.v3.TagValues/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @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 access control policy on a TagValue, replacing any + existing policy. The ``resource`` field should be the TagValue's + resource name. For example: ``tagValues/1234``. The caller must + have ``resourcemanager.tagValues.setIamPolicy`` permission on + the identified tagValue. + + 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.cloud.resourcemanager.v3.TagValues/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns permissions that a caller has on the specified TagValue. + The ``resource`` field should be the TagValue's resource name. + For example: ``tagValues/1234``. + + There are no permissions required for making this API call. + + 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.cloud.resourcemanager.v3.TagValues/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'TagValuesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py new file mode 100644 index 0000000..71fc337 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py @@ -0,0 +1,1301 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.resourcemanager_v3.types import tag_values +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 TagValuesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class TagValuesRestInterceptor: + """Interceptor for TagValues. + + 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 TagValuesRestTransport. + + .. code-block:: python + class MyCustomTagValuesInterceptor(TagValuesRestInterceptor): + def pre_create_tag_value(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tag_value(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_tag_value(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_tag_value(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tag_value(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tag_value(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tag_values(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tag_values(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tag_value(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tag_value(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TagValuesRestTransport(interceptor=MyCustomTagValuesInterceptor()) + client = TagValuesClient(transport=transport) + + + """ + def pre_create_tag_value(self, request: tag_values.CreateTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.CreateTagValueRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_tag_value + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagValues server. + """ + return request, metadata + + def post_create_tag_value(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_tag_value + + Override in a subclass to manipulate the response + after it is returned by the TagValues server but before + it is returned to user code. + """ + return response + def pre_delete_tag_value(self, request: tag_values.DeleteTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.DeleteTagValueRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_tag_value + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagValues server. + """ + return request, metadata + + def post_delete_tag_value(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_tag_value + + Override in a subclass to manipulate the response + after it is returned by the TagValues 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 TagValues 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 TagValues server but before + it is returned to user code. + """ + return response + def pre_get_tag_value(self, request: tag_values.GetTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.GetTagValueRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_tag_value + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagValues server. + """ + return request, metadata + + def post_get_tag_value(self, response: tag_values.TagValue) -> tag_values.TagValue: + """Post-rpc interceptor for get_tag_value + + Override in a subclass to manipulate the response + after it is returned by the TagValues server but before + it is returned to user code. + """ + return response + def pre_list_tag_values(self, request: tag_values.ListTagValuesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.ListTagValuesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_tag_values + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagValues server. + """ + return request, metadata + + def post_list_tag_values(self, response: tag_values.ListTagValuesResponse) -> tag_values.ListTagValuesResponse: + """Post-rpc interceptor for list_tag_values + + Override in a subclass to manipulate the response + after it is returned by the TagValues 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 TagValues 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 TagValues 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 TagValues 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 TagValues server but before + it is returned to user code. + """ + return response + def pre_update_tag_value(self, request: tag_values.UpdateTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.UpdateTagValueRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_tag_value + + Override in a subclass to manipulate the request or metadata + before they are sent to the TagValues server. + """ + return request, metadata + + def post_update_tag_value(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_tag_value + + Override in a subclass to manipulate the response + after it is returned by the TagValues server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class TagValuesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TagValuesRestInterceptor + + +class TagValuesRestTransport(TagValuesTransport): + """REST backend transport for TagValues. + + Allow users to create and manage tag values. + + 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 = 'cloudresourcemanager.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[TagValuesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or TagValuesRestInterceptor() + 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': '/v3/{name=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="v3") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateTagValue(TagValuesRestStub): + def __hash__(self): + return hash("CreateTagValue") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_values.CreateTagValueRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create tag value method over HTTP. + + Args: + request (~.tag_values.CreateTagValueRequest): + The request object. The request message for creating a + TagValue. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/tagValues', + 'body': 'tag_value', + }, + ] + request, metadata = self._interceptor.pre_create_tag_value(request, metadata) + pb_request = tag_values.CreateTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_tag_value(resp) + return resp + + class _DeleteTagValue(TagValuesRestStub): + def __hash__(self): + return hash("DeleteTagValue") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_values.DeleteTagValueRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete tag value method over HTTP. + + Args: + request (~.tag_values.DeleteTagValueRequest): + The request object. The request message for deleting a + TagValue. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v3/{name=tagValues/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_tag_value(request, metadata) + pb_request = tag_values.DeleteTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_tag_value(resp) + return resp + + class _GetIamPolicy(TagValuesRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=tagValues/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetTagValue(TagValuesRestStub): + def __hash__(self): + return hash("GetTagValue") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_values.GetTagValueRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tag_values.TagValue: + r"""Call the get tag value method over HTTP. + + Args: + request (~.tag_values.GetTagValueRequest): + The request object. The request message for getting a + TagValue. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tag_values.TagValue: + A TagValue is a child of a particular + TagKey. This is used to group cloud + resources for the purpose of controlling + them using policies. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/{name=tagValues/*}', + }, + ] + request, metadata = self._interceptor.pre_get_tag_value(request, metadata) + pb_request = tag_values.GetTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tag_values.TagValue() + pb_resp = tag_values.TagValue.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_tag_value(resp) + return resp + + class _ListTagValues(TagValuesRestStub): + def __hash__(self): + return hash("ListTagValues") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_values.ListTagValuesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> tag_values.ListTagValuesResponse: + r"""Call the list tag values method over HTTP. + + Args: + request (~.tag_values.ListTagValuesRequest): + The request object. The request message for listing + TagValues for the specified TagKey. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.tag_values.ListTagValuesResponse: + The ListTagValues response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v3/tagValues', + }, + ] + request, metadata = self._interceptor.pre_list_tag_values(request, metadata) + pb_request = tag_values.ListTagValuesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tag_values.ListTagValuesResponse() + pb_resp = tag_values.ListTagValuesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_tag_values(resp) + return resp + + class _SetIamPolicy(TagValuesRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **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')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **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') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=tagValues/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(TagValuesRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: 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. 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v3/{resource=tagValues/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateTagValue(TagValuesRestStub): + def __hash__(self): + return hash("UpdateTagValue") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: tag_values.UpdateTagValueRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update tag value method over HTTP. + + Args: + request (~.tag_values.UpdateTagValueRequest): + The request object. The request message for updating a + TagValue. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v3/{tag_value.name=tagValues/*}', + 'body': 'tag_value', + }, + ] + request, metadata = self._interceptor.pre_update_tag_value(request, metadata) + pb_request = tag_values.UpdateTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_tag_value(resp) + return resp + + @property + def create_tag_value(self) -> Callable[ + [tag_values.CreateTagValueRequest], + 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._CreateTagValue(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tag_value(self) -> Callable[ + [tag_values.DeleteTagValueRequest], + 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._DeleteTagValue(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tag_value(self) -> Callable[ + [tag_values.GetTagValueRequest], + tag_values.TagValue]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTagValue(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tag_values(self) -> Callable[ + [tag_values.ListTagValuesRequest], + tag_values.ListTagValuesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTagValues(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tag_value(self) -> Callable[ + [tag_values.UpdateTagValueRequest], + 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._UpdateTagValue(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TagValuesRestTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py new file mode 100644 index 0000000..37c36b4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .folders import ( + CreateFolderMetadata, + CreateFolderRequest, + DeleteFolderMetadata, + DeleteFolderRequest, + Folder, + GetFolderRequest, + ListFoldersRequest, + ListFoldersResponse, + MoveFolderMetadata, + MoveFolderRequest, + SearchFoldersRequest, + SearchFoldersResponse, + UndeleteFolderMetadata, + UndeleteFolderRequest, + UpdateFolderMetadata, + UpdateFolderRequest, +) +from .organizations import ( + DeleteOrganizationMetadata, + GetOrganizationRequest, + Organization, + SearchOrganizationsRequest, + SearchOrganizationsResponse, + UndeleteOrganizationMetadata, +) +from .projects import ( + CreateProjectMetadata, + CreateProjectRequest, + DeleteProjectMetadata, + DeleteProjectRequest, + GetProjectRequest, + ListProjectsRequest, + ListProjectsResponse, + MoveProjectMetadata, + MoveProjectRequest, + Project, + SearchProjectsRequest, + SearchProjectsResponse, + UndeleteProjectMetadata, + UndeleteProjectRequest, + UpdateProjectMetadata, + UpdateProjectRequest, +) +from .tag_bindings import ( + CreateTagBindingMetadata, + CreateTagBindingRequest, + DeleteTagBindingMetadata, + DeleteTagBindingRequest, + ListTagBindingsRequest, + ListTagBindingsResponse, + TagBinding, +) +from .tag_keys import ( + CreateTagKeyMetadata, + CreateTagKeyRequest, + DeleteTagKeyMetadata, + DeleteTagKeyRequest, + GetTagKeyRequest, + ListTagKeysRequest, + ListTagKeysResponse, + TagKey, + UpdateTagKeyMetadata, + UpdateTagKeyRequest, +) +from .tag_values import ( + CreateTagValueMetadata, + CreateTagValueRequest, + DeleteTagValueMetadata, + DeleteTagValueRequest, + GetTagValueRequest, + ListTagValuesRequest, + ListTagValuesResponse, + TagValue, + UpdateTagValueMetadata, + UpdateTagValueRequest, +) + +__all__ = ( + 'CreateFolderMetadata', + 'CreateFolderRequest', + 'DeleteFolderMetadata', + 'DeleteFolderRequest', + 'Folder', + 'GetFolderRequest', + 'ListFoldersRequest', + 'ListFoldersResponse', + 'MoveFolderMetadata', + 'MoveFolderRequest', + 'SearchFoldersRequest', + 'SearchFoldersResponse', + 'UndeleteFolderMetadata', + 'UndeleteFolderRequest', + 'UpdateFolderMetadata', + 'UpdateFolderRequest', + 'DeleteOrganizationMetadata', + 'GetOrganizationRequest', + 'Organization', + 'SearchOrganizationsRequest', + 'SearchOrganizationsResponse', + 'UndeleteOrganizationMetadata', + 'CreateProjectMetadata', + 'CreateProjectRequest', + 'DeleteProjectMetadata', + 'DeleteProjectRequest', + 'GetProjectRequest', + 'ListProjectsRequest', + 'ListProjectsResponse', + 'MoveProjectMetadata', + 'MoveProjectRequest', + 'Project', + 'SearchProjectsRequest', + 'SearchProjectsResponse', + 'UndeleteProjectMetadata', + 'UndeleteProjectRequest', + 'UpdateProjectMetadata', + 'UpdateProjectRequest', + 'CreateTagBindingMetadata', + 'CreateTagBindingRequest', + 'DeleteTagBindingMetadata', + 'DeleteTagBindingRequest', + 'ListTagBindingsRequest', + 'ListTagBindingsResponse', + 'TagBinding', + 'CreateTagKeyMetadata', + 'CreateTagKeyRequest', + 'DeleteTagKeyMetadata', + 'DeleteTagKeyRequest', + 'GetTagKeyRequest', + 'ListTagKeysRequest', + 'ListTagKeysResponse', + 'TagKey', + 'UpdateTagKeyMetadata', + 'UpdateTagKeyRequest', + 'CreateTagValueMetadata', + 'CreateTagValueRequest', + 'DeleteTagValueMetadata', + 'DeleteTagValueRequest', + 'GetTagValueRequest', + 'ListTagValuesRequest', + 'ListTagValuesResponse', + 'TagValue', + 'UpdateTagValueMetadata', + 'UpdateTagValueRequest', +) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py new file mode 100644 index 0000000..9dc4606 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py @@ -0,0 +1,495 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager.v3', + manifest={ + 'Folder', + 'GetFolderRequest', + 'ListFoldersRequest', + 'ListFoldersResponse', + 'SearchFoldersRequest', + 'SearchFoldersResponse', + 'CreateFolderRequest', + 'CreateFolderMetadata', + 'UpdateFolderRequest', + 'UpdateFolderMetadata', + 'MoveFolderRequest', + 'MoveFolderMetadata', + 'DeleteFolderRequest', + 'DeleteFolderMetadata', + 'UndeleteFolderRequest', + 'UndeleteFolderMetadata', + }, +) + + +class Folder(proto.Message): + r"""A folder in an organization's resource hierarchy, used to + organize that organization's resources. + + Attributes: + name (str): + Output only. The resource name of the folder. Its format is + ``folders/{folder_id}``, for example: "folders/1234". + parent (str): + Required. The folder's parent's resource name. Updates to + the folder's parent must be performed using + [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder]. + display_name (str): + The folder's display name. A folder's display name must be + unique amongst its siblings. For example, no two folders + with the same parent can share the same display name. The + display name must start and end with a letter or digit, may + contain letters, digits, spaces, hyphens and underscores and + can be no longer than 30 characters. This is captured by the + regular expression: + ``[\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?``. + state (google.cloud.resourcemanager_v3.types.Folder.State): + Output only. The lifecycle state of the folder. Updates to + the state must be performed using + [DeleteFolder][google.cloud.resourcemanager.v3.Folders.DeleteFolder] + and + [UndeleteFolder][google.cloud.resourcemanager.v3.Folders.UndeleteFolder]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the folder was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the folder was + last modified. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the folder was + requested to be deleted. + etag (str): + Output only. A checksum computed by the + server based on the current value of the folder + resource. This may be sent on update and delete + requests to ensure the client has an up-to-date + value before proceeding. + """ + class State(proto.Enum): + r"""Folder lifecycle states. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + ACTIVE (1): + The normal and active state. + DELETE_REQUESTED (2): + The folder has been marked for deletion by + the user. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + DELETE_REQUESTED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=8, + ) + + +class GetFolderRequest(proto.Message): + r"""The GetFolder request message. + + Attributes: + name (str): + Required. The resource name of the folder to retrieve. Must + be of the form ``folders/{folder_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFoldersRequest(proto.Message): + r"""The ListFolders request message. + + Attributes: + parent (str): + Required. The resource name of the organization or folder + whose folders are being listed. Must be of the form + ``folders/{folder_id}`` or ``organizations/{org_id}``. + Access to this method is controlled by checking the + ``resourcemanager.folders.list`` permission on the + ``parent``. + page_size (int): + Optional. The maximum number of folders to + return in the response. If unspecified, server + picks an appropriate default. + page_token (str): + Optional. A pagination token returned from a previous call + to ``ListFolders`` that indicates where this listing should + continue from. + show_deleted (bool): + Optional. Controls whether folders in the + [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] + state should be returned. Defaults to false. + """ + + 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListFoldersResponse(proto.Message): + r"""The ListFolders response message. + + Attributes: + folders (MutableSequence[google.cloud.resourcemanager_v3.types.Folder]): + A possibly paginated list of folders that are + direct descendants of the specified parent + resource. + next_page_token (str): + A pagination token returned from a previous call to + ``ListFolders`` that indicates from where listing should + continue. + """ + + @property + def raw_page(self): + return self + + folders: MutableSequence['Folder'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Folder', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchFoldersRequest(proto.Message): + r"""The request message for searching folders. + + Attributes: + page_size (int): + Optional. The maximum number of folders to + return in the response. If unspecified, server + picks an appropriate default. + page_token (str): + Optional. A pagination token returned from a previous call + to ``SearchFolders`` that indicates from where search should + continue. + query (str): + Optional. Search criteria used to select the folders to + return. If no search criteria is specified then all + accessible folders will be returned. + + Query expressions can be used to restrict results based upon + displayName, state and parent, where the operators ``=`` + (``:``) ``NOT``, ``AND`` and ``OR`` can be used along with + the suffix wildcard symbol ``*``. + + The ``displayName`` field in a query expression should use + escaped quotes for values that include whitespace to prevent + unexpected behavior. + + :: + + | Field | Description | + |-------------------------|----------------------------------------| + | displayName | Filters by displayName. | + | parent | Filters by parent (for example: folders/123). | + | state, lifecycleState | Filters by state. | + + Some example queries are: + + - Query ``displayName=Test*`` returns Folder resources + whose display name starts with "Test". + - Query ``state=ACTIVE`` returns Folder resources with + ``state`` set to ``ACTIVE``. + - Query ``parent=folders/123`` returns Folder resources + that have ``folders/123`` as a parent resource. + - Query ``parent=folders/123 AND state=ACTIVE`` returns + active Folder resources that have ``folders/123`` as a + parent resource. + - Query ``displayName=\\"Test String\\"`` returns Folder + resources with display names that include both "Test" and + "String". + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchFoldersResponse(proto.Message): + r"""The response message for searching folders. + + Attributes: + folders (MutableSequence[google.cloud.resourcemanager_v3.types.Folder]): + A possibly paginated folder search results. + the specified parent resource. + next_page_token (str): + A pagination token returned from a previous call to + ``SearchFolders`` that indicates from where searching should + continue. + """ + + @property + def raw_page(self): + return self + + folders: MutableSequence['Folder'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Folder', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateFolderRequest(proto.Message): + r"""The CreateFolder request message. + + Attributes: + folder (google.cloud.resourcemanager_v3.types.Folder): + Required. The folder being created, only the + display name and parent will be consulted. All + other fields will be ignored. + """ + + folder: 'Folder' = proto.Field( + proto.MESSAGE, + number=2, + message='Folder', + ) + + +class CreateFolderMetadata(proto.Message): + r"""Metadata pertaining to the Folder creation process. + + Attributes: + display_name (str): + The display name of the folder. + parent (str): + The resource name of the folder or + organization we are creating the folder under. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateFolderRequest(proto.Message): + r"""The request sent to the + [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] + method. + + Only the ``display_name`` field can be changed. All other fields + will be ignored. Use the + [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] + method to change the ``parent`` field. + + Attributes: + folder (google.cloud.resourcemanager_v3.types.Folder): + Required. The new definition of the Folder. It must include + the ``name`` field, which cannot be changed. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Fields to be updated. Only the ``display_name`` + can be updated. + """ + + folder: 'Folder' = proto.Field( + proto.MESSAGE, + number=1, + message='Folder', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateFolderMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by UpdateFolder. + + """ + + +class MoveFolderRequest(proto.Message): + r"""The MoveFolder request message. + + Attributes: + name (str): + Required. The resource name of the Folder to move. Must be + of the form folders/{folder_id} + destination_parent (str): + Required. The resource name of the folder or organization + which should be the folder's new parent. Must be of the form + ``folders/{folder_id}`` or ``organizations/{org_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + destination_parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MoveFolderMetadata(proto.Message): + r"""Metadata pertaining to the folder move process. + + Attributes: + display_name (str): + The display name of the folder. + source_parent (str): + The resource name of the folder's parent. + destination_parent (str): + The resource name of the folder or + organization to move the folder to. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + source_parent: str = proto.Field( + proto.STRING, + number=2, + ) + destination_parent: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFolderRequest(proto.Message): + r"""The DeleteFolder request message. + + Attributes: + name (str): + Required. The resource name of the folder to be deleted. + Must be of the form ``folders/{folder_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteFolderMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + ``Operation`` returned by ``DeleteFolder``. + + """ + + +class UndeleteFolderRequest(proto.Message): + r"""The UndeleteFolder request message. + + Attributes: + name (str): + Required. The resource name of the folder to undelete. Must + be of the form ``folders/{folder_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteFolderMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + ``Operation`` returned by ``UndeleteFolder``. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py new file mode 100644 index 0000000..e2395b0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.resourcemanager.v3', + manifest={ + 'Organization', + 'GetOrganizationRequest', + 'SearchOrganizationsRequest', + 'SearchOrganizationsResponse', + 'DeleteOrganizationMetadata', + 'UndeleteOrganizationMetadata', + }, +) + + +class Organization(proto.Message): + r"""The root node in the resource hierarchy to which a particular + entity's (a company, for example) resources belong. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The resource name of the organization. This is + the organization's relative path in the API. Its format is + "organizations/[organization_id]". For example, + "organizations/1234". + display_name (str): + Output only. A human-readable string that + refers to the organization in the Google Cloud + Console. This string is set by the server and + cannot be changed. The string will be set to the + primary domain (for example, "google.com") of + the Google Workspace customer that owns the + organization. + directory_customer_id (str): + Immutable. The G Suite / Workspace customer + id used in the Directory API. + + This field is a member of `oneof`_ ``owner``. + state (google.cloud.resourcemanager_v3.types.Organization.State): + Output only. The organization's current + lifecycle state. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the Organization + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the Organization + was last modified. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the Organization + was requested for deletion. + etag (str): + Output only. A checksum computed by the + server based on the current value of the + Organization resource. This may be sent on + update and delete requests to ensure the client + has an up-to-date value before proceeding. + """ + class State(proto.Enum): + r"""Organization lifecycle states. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. This is only useful for + distinguishing unset values. + ACTIVE (1): + The normal and active state. + DELETE_REQUESTED (2): + The organization has been marked for deletion + by the user. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + DELETE_REQUESTED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + directory_customer_id: str = proto.Field( + proto.STRING, + number=3, + oneof='owner', + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=8, + ) + + +class GetOrganizationRequest(proto.Message): + r"""The request sent to the ``GetOrganization`` method. The ``name`` + field is required. ``organization_id`` is no longer accepted. + + Attributes: + name (str): + Required. The resource name of the Organization to fetch. + This is the organization's relative path in the API, + formatted as "organizations/[organizationId]". For example, + "organizations/1234". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SearchOrganizationsRequest(proto.Message): + r"""The request sent to the ``SearchOrganizations`` method. + + Attributes: + page_size (int): + Optional. The maximum number of organizations + to return in the response. If unspecified, + server picks an appropriate default. + page_token (str): + Optional. A pagination token returned from a previous call + to ``SearchOrganizations`` that indicates from where listing + should continue. + query (str): + Optional. An optional query string used to filter the + Organizations to return in the response. Query rules are + case-insensitive. + + :: + + | Field | Description | + |------------------|--------------------------------------------| + | directoryCustomerId, owner.directoryCustomerId | Filters by directory + customer id. | + | domain | Filters by domain. | + + Organizations may be queried by ``directoryCustomerId`` or + by ``domain``, where the domain is a G Suite domain, for + example: + + - Query ``directorycustomerid:123456789`` returns + Organization resources with + ``owner.directory_customer_id`` equal to ``123456789``. + - Query ``domain:google.com`` returns Organization + resources corresponding to the domain ``google.com``. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + + +class SearchOrganizationsResponse(proto.Message): + r"""The response returned from the ``SearchOrganizations`` method. + + Attributes: + organizations (MutableSequence[google.cloud.resourcemanager_v3.types.Organization]): + The list of Organizations that matched the + search query, possibly paginated. + next_page_token (str): + A pagination token to be used to retrieve the + next page of results. If the result is too large + to fit within the page size specified in the + request, this field will be set with a token + that can be used to fetch the next page of + results. If this field is empty, it indicates + that this response contains the last page of + results. + """ + + @property + def raw_page(self): + return self + + organizations: MutableSequence['Organization'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Organization', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteOrganizationMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + operation returned by DeleteOrganization. + + """ + + +class UndeleteOrganizationMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by UndeleteOrganization. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py new file mode 100644 index 0000000..2e28b9a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py @@ -0,0 +1,584 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager.v3', + manifest={ + 'Project', + 'GetProjectRequest', + 'ListProjectsRequest', + 'ListProjectsResponse', + 'SearchProjectsRequest', + 'SearchProjectsResponse', + 'CreateProjectRequest', + 'CreateProjectMetadata', + 'UpdateProjectRequest', + 'UpdateProjectMetadata', + 'MoveProjectRequest', + 'MoveProjectMetadata', + 'DeleteProjectRequest', + 'DeleteProjectMetadata', + 'UndeleteProjectRequest', + 'UndeleteProjectMetadata', + }, +) + + +class Project(proto.Message): + r"""A project is a high-level Google Cloud entity. It is a + container for ACLs, APIs, App Engine Apps, VMs, and other Google + Cloud Platform resources. + + Attributes: + name (str): + Output only. The unique resource name of the project. It is + an int64 generated number prefixed by "projects/". + + Example: ``projects/415104041262`` + parent (str): + Optional. A reference to a parent Resource. eg., + ``organizations/123`` or ``folders/876``. + project_id (str): + Immutable. The unique, user-assigned id of the project. It + must be 6 to 30 lowercase ASCII letters, digits, or hyphens. + It must start with a letter. Trailing hyphens are + prohibited. + + Example: ``tokyo-rain-123`` + state (google.cloud.resourcemanager_v3.types.Project.State): + Output only. The project lifecycle state. + display_name (str): + Optional. A user-assigned display name of the project. When + present it must be between 4 to 30 characters. Allowed + characters are: lowercase and uppercase letters, numbers, + hyphen, single-quote, double-quote, space, and exclamation + point. + + Example: ``My Project`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + resource was modified. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this resource + was requested for deletion. + etag (str): + Output only. A checksum computed by the + server based on the current value of the Project + resource. This may be sent on update and delete + requests to ensure the client has an up-to-date + value before proceeding. + labels (MutableMapping[str, str]): + Optional. The labels associated with this project. + + Label keys must be between 1 and 63 characters long and must + conform to the following regular expression: + [a-z]([-a-z0-9]*[a-z0-9])?. + + Label values must be between 0 and 63 characters long and + must conform to the regular expression + ([a-z]([-a-z0-9]*[a-z0-9])?)?. + + No more than 256 labels can be associated with a given + resource. + + Clients should store labels in a representation such as JSON + that does not depend on specific characters being + disallowed. + + Example: ``"myBusinessDimension" : "businessValue"`` + """ + class State(proto.Enum): + r"""Project lifecycle states. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. This is only used/useful + for distinguishing unset values. + ACTIVE (1): + The normal and active state. + DELETE_REQUESTED (2): + The project has been marked for deletion by the user (by + invoking + [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject]) + or by the system (Google Cloud Platform). This can generally + be reversed by invoking [UndeleteProject] + [google.cloud.resourcemanager.v3.Projects.UndeleteProject]. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + DELETE_REQUESTED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + project_id: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class GetProjectRequest(proto.Message): + r"""The request sent to the + [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] + method. + + Attributes: + name (str): + Required. The name of the project (for example, + ``projects/415104041262``). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProjectsRequest(proto.Message): + r"""The request sent to the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + + Attributes: + parent (str): + Required. The name of the parent resource to + list projects under. + For example, setting this field to + 'folders/1234' would list all projects directly + under that folder. + page_token (str): + Optional. A pagination token returned from a previous call + to [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects] that + indicates from where listing should continue. + page_size (int): + Optional. The maximum number of projects to + return in the response. The server can return + fewer projects than requested. If unspecified, + server picks an appropriate default. + show_deleted (bool): + Optional. Indicate that projects in the ``DELETE_REQUESTED`` + state should also be returned. Normally only ``ACTIVE`` + projects are returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListProjectsResponse(proto.Message): + r"""A page of the response received from the + [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] + method. + + A paginated response where more pages are available has + ``next_page_token`` set. This token can be used in a subsequent + request to retrieve the next request page. + + NOTE: A response may contain fewer elements than the request + ``page_size`` and still have a ``next_page_token``. + + Attributes: + projects (MutableSequence[google.cloud.resourcemanager_v3.types.Project]): + The list of Projects under the parent. This + list can be paginated. + next_page_token (str): + Pagination token. + + If the result set is too large to fit in a single response, + this token is returned. It encodes the position of the + current result cursor. Feeding this value into a new list + request with the ``page_token`` parameter gives the next + page of the results. + + When ``next_page_token`` is not filled in, there is no next + page and the list returned is the last page in the result + set. + + Pagination tokens have a limited lifetime. + """ + + @property + def raw_page(self): + return self + + projects: MutableSequence['Project'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Project', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchProjectsRequest(proto.Message): + r"""The request sent to the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + + Attributes: + query (str): + Optional. A query string for searching for projects that the + caller has ``resourcemanager.projects.get`` permission to. + If multiple fields are included in the query, the it will + return results that match any of the fields. Some eligible + fields are: + + :: + + | Field | Description | + |-------------------------|----------------------------------------------| + | displayName, name | Filters by displayName. | + | parent | Project's parent. (for example: folders/123, + organizations/*) Prefer parent field over parent.type and parent.id. | + | parent.type | Parent's type: `folder` or `organization`. | + | parent.id | Parent's id number (for example: 123) | + | id, projectId | Filters by projectId. | + | state, lifecycleState | Filters by state. | + | labels | Filters by label name or value. | + | labels. (where *key* is the name of a label) | Filters by label + name. | + + Search expressions are case insensitive. + + Some examples queries: + + :: + + | Query | Description | + |------------------|-----------------------------------------------------| + | name:how* | The project's name starts with "how". | + | name:Howl | The project's name is `Howl` or `howl`. | + | name:HOWL | Equivalent to above. | + | NAME:howl | Equivalent to above. | + | labels.color:* | The project has the label `color`. | + | labels.color:red | The project's label `color` has the value `red`. | + | labels.color:red labels.size:big | The project's label `color` has + the value `red` and its label `size` has the value `big`. | + + If no query is specified, the call will return projects for + which the user has the ``resourcemanager.projects.get`` + permission. + page_token (str): + Optional. A pagination token returned from a previous call + to [ListProjects] + [google.cloud.resourcemanager.v3.Projects.ListProjects] that + indicates from where listing should continue. + page_size (int): + Optional. The maximum number of projects to + return in the response. The server can return + fewer projects than requested. If unspecified, + server picks an appropriate default. + """ + + query: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class SearchProjectsResponse(proto.Message): + r"""A page of the response received from the + [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] + method. + + A paginated response where more pages are available has + ``next_page_token`` set. This token can be used in a subsequent + request to retrieve the next request page. + + Attributes: + projects (MutableSequence[google.cloud.resourcemanager_v3.types.Project]): + The list of Projects that matched the list + filter query. This list can be paginated. + next_page_token (str): + Pagination token. + + If the result set is too large to fit in a single response, + this token is returned. It encodes the position of the + current result cursor. Feeding this value into a new list + request with the ``page_token`` parameter gives the next + page of the results. + + When ``next_page_token`` is not filled in, there is no next + page and the list returned is the last page in the result + set. + + Pagination tokens have a limited lifetime. + """ + + @property + def raw_page(self): + return self + + projects: MutableSequence['Project'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Project', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateProjectRequest(proto.Message): + r"""The request sent to the + [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] + method. + + Attributes: + project (google.cloud.resourcemanager_v3.types.Project): + Required. The Project to create. + + Project ID is required. If the requested ID is unavailable, + the request fails. + + If the ``parent`` field is set, the + ``resourcemanager.projects.create`` permission is checked on + the parent resource. If no parent is set and the + authorization credentials belong to an Organziation, the + parent will be set to that Organization. + """ + + project: 'Project' = proto.Field( + proto.MESSAGE, + number=1, + message='Project', + ) + + +class CreateProjectMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by CreateProject. It provides insight for when + significant phases of Project creation have completed. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Creation time of the project creation + workflow. + gettable (bool): + True if the project can be retrieved using ``GetProject``. + No other operations on the project are guaranteed to work + until the project creation is complete. + ready (bool): + True if the project creation process is + complete. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + gettable: bool = proto.Field( + proto.BOOL, + number=2, + ) + ready: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class UpdateProjectRequest(proto.Message): + r"""The request sent to the + [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] + method. + + Only the ``display_name`` and ``labels`` fields can be change. Use + the + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method to change the ``parent`` field. + + Attributes: + project (google.cloud.resourcemanager_v3.types.Project): + Required. The new definition of the project. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. An update mask to selectively + update fields. + """ + + project: 'Project' = proto.Field( + proto.MESSAGE, + number=1, + message='Project', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateProjectMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by UpdateProject. + + """ + + +class MoveProjectRequest(proto.Message): + r"""The request sent to + [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] + method. + + Attributes: + name (str): + Required. The name of the project to move. + destination_parent (str): + Required. The new parent to move the Project + under. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + destination_parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MoveProjectMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by MoveProject. + + """ + + +class DeleteProjectRequest(proto.Message): + r"""[DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] + method. + + Attributes: + name (str): + Required. The name of the Project (for example, + ``projects/415104041262``). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteProjectMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by ``DeleteProject``. + + """ + + +class UndeleteProjectRequest(proto.Message): + r"""The request sent to the [UndeleteProject] + [google.cloud.resourcemanager.v3.Projects.UndeleteProject] method. + + Attributes: + name (str): + Required. The name of the project (for example, + ``projects/415104041262``). + + Required. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteProjectMetadata(proto.Message): + r"""A status object which is used as the ``metadata`` field for the + Operation returned by ``UndeleteProject``. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py new file mode 100644 index 0000000..5b10775 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager.v3', + manifest={ + 'TagBinding', + 'CreateTagBindingMetadata', + 'CreateTagBindingRequest', + 'DeleteTagBindingMetadata', + 'DeleteTagBindingRequest', + 'ListTagBindingsRequest', + 'ListTagBindingsResponse', + }, +) + + +class TagBinding(proto.Message): + r"""A TagBinding represents a connection between a TagValue and a + cloud resource (currently project, folder, or organization). + Once a TagBinding is created, the TagValue is applied to all the + descendants of the cloud resource. + + Attributes: + name (str): + Output only. The name of the TagBinding. This is a String of + the form: + ``tagBindings/{full-resource-name}/{tag-value-name}`` (e.g. + ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). + parent (str): + The full resource name of the resource the TagValue is bound + to. E.g. + ``//cloudresourcemanager.googleapis.com/projects/123`` + tag_value (str): + The TagValue of the TagBinding. Must be of the form + ``tagValues/456``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + tag_value: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateTagBindingMetadata(proto.Message): + r"""Runtime operation information for creating a TagValue. + """ + + +class CreateTagBindingRequest(proto.Message): + r"""The request message to create a TagBinding. + + Attributes: + tag_binding (google.cloud.resourcemanager_v3.types.TagBinding): + Required. The TagBinding to be created. + validate_only (bool): + Optional. Set to true to perform the + validations necessary for creating the resource, + but not actually perform the action. + """ + + tag_binding: 'TagBinding' = proto.Field( + proto.MESSAGE, + number=1, + message='TagBinding', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class DeleteTagBindingMetadata(proto.Message): + r"""Runtime operation information for deleting a TagBinding. + """ + + +class DeleteTagBindingRequest(proto.Message): + r"""The request message to delete a TagBinding. + + Attributes: + name (str): + Required. The name of the TagBinding. This is a String of + the form: ``tagBindings/{id}`` (e.g. + ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListTagBindingsRequest(proto.Message): + r"""The request message to list all TagBindings for a parent. + + Attributes: + parent (str): + Required. The full resource name of a + resource for which you want to list existing + TagBindings. E.g. + "//cloudresourcemanager.googleapis.com/projects/123". + page_size (int): + Optional. The maximum number of TagBindings + to return in the response. The server allows a + maximum of 300 TagBindings to return. If + unspecified, the server will use 100 as the + default. + page_token (str): + Optional. A pagination token returned from a previous call + to ``ListTagBindings`` that indicates where this listing + should continue from. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTagBindingsResponse(proto.Message): + r"""The ListTagBindings response. + + Attributes: + tag_bindings (MutableSequence[google.cloud.resourcemanager_v3.types.TagBinding]): + A possibly paginated list of TagBindings for + the specified TagValue or resource. + next_page_token (str): + Pagination token. + + If the result set is too large to fit in a single response, + this token is returned. It encodes the position of the + current result cursor. Feeding this value into a new list + request with the ``page_token`` parameter gives the next + page of the results. + + When ``next_page_token`` is not filled in, there is no next + page and the list returned is the last page in the result + set. + + Pagination tokens have a limited lifetime. + """ + + @property + def raw_page(self): + return self + + tag_bindings: MutableSequence['TagBinding'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TagBinding', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py new file mode 100644 index 0000000..4132ed8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager.v3', + manifest={ + 'TagKey', + 'ListTagKeysRequest', + 'ListTagKeysResponse', + 'GetTagKeyRequest', + 'CreateTagKeyRequest', + 'CreateTagKeyMetadata', + 'UpdateTagKeyRequest', + 'UpdateTagKeyMetadata', + 'DeleteTagKeyRequest', + 'DeleteTagKeyMetadata', + }, +) + + +class TagKey(proto.Message): + r"""A TagKey, used to group a set of TagValues. + + Attributes: + name (str): + Immutable. The resource name for a TagKey. Must be in the + format ``tagKeys/{tag_key_id}``, where ``tag_key_id`` is the + generated numeric id for the TagKey. + parent (str): + Immutable. The resource name of the new TagKey's parent. + Must be of the form ``organizations/{org_id}``. + short_name (str): + Required. Immutable. The user friendly name for a TagKey. + The short name should be unique for TagKeys within the same + tag namespace. + + The short name must be 1-63 characters, beginning and ending + with an alphanumeric character ([a-z0-9A-Z]) with dashes + (-), underscores (_), dots (.), and alphanumerics between. + namespaced_name (str): + Output only. Immutable. Namespaced name of + the TagKey. + description (str): + Optional. User-assigned description of the + TagKey. Must not exceed 256 characters. + Read-write. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time. + etag (str): + Optional. Entity tag which users can pass to + prevent race conditions. This field is always + set in server responses. See UpdateTagKeyRequest + for details. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + short_name: str = proto.Field( + proto.STRING, + number=3, + ) + namespaced_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=8, + ) + + +class ListTagKeysRequest(proto.Message): + r"""The request message for listing all TagKeys under a parent + resource. + + Attributes: + parent (str): + Required. The resource name of the new TagKey's parent. Must + be of the form ``folders/{folder_id}`` or + ``organizations/{org_id}``. + page_size (int): + Optional. The maximum number of TagKeys to + return in the response. The server allows a + maximum of 300 TagKeys to return. If + unspecified, the server will use 100 as the + default. + page_token (str): + Optional. A pagination token returned from a previous call + to ``ListTagKey`` that indicates where this listing should + continue from. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTagKeysResponse(proto.Message): + r"""The ListTagKeys response message. + + Attributes: + tag_keys (MutableSequence[google.cloud.resourcemanager_v3.types.TagKey]): + List of TagKeys that live under the specified + parent in the request. + next_page_token (str): + A pagination token returned from a previous call to + ``ListTagKeys`` that indicates from where listing should + continue. + """ + + @property + def raw_page(self): + return self + + tag_keys: MutableSequence['TagKey'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TagKey', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTagKeyRequest(proto.Message): + r"""The request message for getting a TagKey. + + Attributes: + name (str): + Required. A resource name in the format ``tagKeys/{id}``, + such as ``tagKeys/123``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTagKeyRequest(proto.Message): + r"""The request message for creating a TagKey. + + Attributes: + tag_key (google.cloud.resourcemanager_v3.types.TagKey): + Required. The TagKey to be created. Only fields + ``short_name``, ``description``, and ``parent`` are + considered during the creation request. + validate_only (bool): + Optional. Set to true to perform validations + necessary for creating the resource, but not + actually perform the action. + """ + + tag_key: 'TagKey' = proto.Field( + proto.MESSAGE, + number=1, + message='TagKey', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class CreateTagKeyMetadata(proto.Message): + r"""Runtime operation information for creating a TagKey. + """ + + +class UpdateTagKeyRequest(proto.Message): + r"""The request message for updating a TagKey. + + Attributes: + tag_key (google.cloud.resourcemanager_v3.types.TagKey): + Required. The new definition of the TagKey. Only the + ``description`` and ``etag`` fields can be updated by this + request. If the ``etag`` field is not empty, it must match + the ``etag`` field of the existing tag key. Otherwise, + ``FAILED_PRECONDITION`` will be returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Fields to be updated. The mask may only contain + ``description`` or ``etag``. If omitted entirely, both + ``description`` and ``etag`` are assumed to be significant. + validate_only (bool): + Set as true to perform validations necessary + for updating the resource, but not actually + perform the action. + """ + + tag_key: 'TagKey' = proto.Field( + proto.MESSAGE, + number=1, + message='TagKey', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class UpdateTagKeyMetadata(proto.Message): + r"""Runtime operation information for updating a TagKey. + """ + + +class DeleteTagKeyRequest(proto.Message): + r"""The request message for deleting a TagKey. + + Attributes: + name (str): + Required. The resource name of a TagKey to be deleted in the + format ``tagKeys/123``. The TagKey cannot be a parent of any + existing TagValues or it will not be deleted successfully. + validate_only (bool): + Optional. Set as true to perform validations + necessary for deletion, but not actually perform + the action. + etag (str): + Optional. The etag known to the client for + the expected state of the TagKey. This is to be + used for optimistic concurrency. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteTagKeyMetadata(proto.Message): + r"""Runtime operation information for deleting a TagKey. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py new file mode 100644 index 0000000..0de3665 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py @@ -0,0 +1,304 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.resourcemanager.v3', + manifest={ + 'TagValue', + 'ListTagValuesRequest', + 'ListTagValuesResponse', + 'GetTagValueRequest', + 'CreateTagValueRequest', + 'CreateTagValueMetadata', + 'UpdateTagValueRequest', + 'UpdateTagValueMetadata', + 'DeleteTagValueRequest', + 'DeleteTagValueMetadata', + }, +) + + +class TagValue(proto.Message): + r"""A TagValue is a child of a particular TagKey. This is used to + group cloud resources for the purpose of controlling them using + policies. + + Attributes: + name (str): + Immutable. Resource name for TagValue in the format + ``tagValues/456``. + parent (str): + Immutable. The resource name of the new TagValue's parent + TagKey. Must be of the form ``tagKeys/{tag_key_id}``. + short_name (str): + Required. Immutable. User-assigned short name for TagValue. + The short name should be unique for TagValues within the + same parent TagKey. + + The short name must be 63 characters or less, beginning and + ending with an alphanumeric character ([a-z0-9A-Z]) with + dashes (-), underscores (_), dots (.), and alphanumerics + between. + namespaced_name (str): + Output only. Namespaced name of the TagValue. Must be in the + format + ``{organization_id}/{tag_key_short_name}/{short_name}``. + description (str): + Optional. User-assigned description of the + TagValue. Must not exceed 256 characters. + + Read-write. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time. + etag (str): + Optional. Entity tag which users can pass to + prevent race conditions. This field is always + set in server responses. See + UpdateTagValueRequest for details. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + short_name: str = proto.Field( + proto.STRING, + number=3, + ) + namespaced_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=8, + ) + + +class ListTagValuesRequest(proto.Message): + r"""The request message for listing TagValues for the specified + TagKey. + + Attributes: + parent (str): + Required. Resource name for TagKey, parent of the TagValues + to be listed, in the format ``tagKeys/123``. + page_size (int): + Optional. The maximum number of TagValues to + return in the response. The server allows a + maximum of 300 TagValues to return. If + unspecified, the server will use 100 as the + default. + page_token (str): + Optional. A pagination token returned from a previous call + to ``ListTagValues`` that indicates where this listing + should continue from. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTagValuesResponse(proto.Message): + r"""The ListTagValues response. + + Attributes: + tag_values (MutableSequence[google.cloud.resourcemanager_v3.types.TagValue]): + A possibly paginated list of TagValues that + are direct descendants of the specified parent + TagKey. + next_page_token (str): + A pagination token returned from a previous call to + ``ListTagValues`` that indicates from where listing should + continue. This is currently not used, but the server may at + any point start supplying a valid token. + """ + + @property + def raw_page(self): + return self + + tag_values: MutableSequence['TagValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TagValue', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTagValueRequest(proto.Message): + r"""The request message for getting a TagValue. + + Attributes: + name (str): + Required. Resource name for TagValue to be fetched in the + format ``tagValues/456``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateTagValueRequest(proto.Message): + r"""The request message for creating a TagValue. + + Attributes: + tag_value (google.cloud.resourcemanager_v3.types.TagValue): + Required. The TagValue to be created. Only fields + ``short_name``, ``description``, and ``parent`` are + considered during the creation request. + validate_only (bool): + Optional. Set as true to perform the + validations necessary for creating the resource, + but not actually perform the action. + """ + + tag_value: 'TagValue' = proto.Field( + proto.MESSAGE, + number=1, + message='TagValue', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class CreateTagValueMetadata(proto.Message): + r"""Runtime operation information for creating a TagValue. + """ + + +class UpdateTagValueRequest(proto.Message): + r"""The request message for updating a TagValue. + + Attributes: + tag_value (google.cloud.resourcemanager_v3.types.TagValue): + Required. The new definition of the TagValue. Only fields + ``description`` and ``etag`` fields can be updated by this + request. If the ``etag`` field is nonempty, it must match + the ``etag`` field of the existing ControlGroup. Otherwise, + ``FAILED_PRECONDITION`` will be returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Fields to be updated. + validate_only (bool): + Optional. True to perform validations + necessary for updating the resource, but not + actually perform the action. + """ + + tag_value: 'TagValue' = proto.Field( + proto.MESSAGE, + number=1, + message='TagValue', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class UpdateTagValueMetadata(proto.Message): + r"""Runtime operation information for updating a TagValue. + """ + + +class DeleteTagValueRequest(proto.Message): + r"""The request message for deleting a TagValue. + + Attributes: + name (str): + Required. Resource name for TagValue to be + deleted in the format tagValues/456. + validate_only (bool): + Optional. Set as true to perform the + validations necessary for deletion, but not + actually perform the action. + etag (str): + Optional. The etag known to the client for + the expected state of the TagValue. This is to + be used for optimistic concurrency. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteTagValueMetadata(proto.Message): + r"""Runtime operation information for deleting a TagValue. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/mypy.ini b/owl-bot-staging/v3/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v3/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v3/noxfile.py b/owl-bot-staging/v3/noxfile.py new file mode 100644 index 0000000..97e57dc --- /dev/null +++ b/owl-bot-staging/v3/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/resourcemanager_v3/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py new file mode 100644 index 0000000..d89b2c1 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_CreateFolder_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_create_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.CreateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.create_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_CreateFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py new file mode 100644 index 0000000..5471a49 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_CreateFolder_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_create_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.CreateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.create_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_CreateFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py new file mode 100644 index 0000000..a07851a --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_DeleteFolder_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_delete_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_DeleteFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py new file mode 100644 index 0000000..91b70c7 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_DeleteFolder_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_delete_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_DeleteFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py new file mode 100644 index 0000000..bfa1fc5 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_GetFolder_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_get_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetFolderRequest( + name="name_value", + ) + + # Make the request + response = await client.get_folder(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_GetFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py new file mode 100644 index 0000000..53416ab --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_GetFolder_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_get_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetFolderRequest( + name="name_value", + ) + + # Make the request + response = client.get_folder(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_GetFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py new file mode 100644 index 0000000..66c59cd --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py new file mode 100644 index 0000000..fcb3417 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py new file mode 100644 index 0000000..11d2f3f --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFolders +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_ListFolders_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_list_folders(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_folders(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_ListFolders_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py new file mode 100644 index 0000000..cba1515 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFolders +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_ListFolders_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_list_folders(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListFoldersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_folders(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_ListFolders_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py new file mode 100644 index 0000000..b843ac9 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_MoveFolder_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_move_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveFolderRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_MoveFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py new file mode 100644 index 0000000..ad3d694 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_MoveFolder_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_move_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveFolderRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_MoveFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py new file mode 100644 index 0000000..36818e0 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchFolders +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_SearchFolders_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_search_folders(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchFoldersRequest( + ) + + # Make the request + page_result = client.search_folders(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_SearchFolders_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py new file mode 100644 index 0000000..b93aba1 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchFolders +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_SearchFolders_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_search_folders(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchFoldersRequest( + ) + + # Make the request + page_result = client.search_folders(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_SearchFolders_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py new file mode 100644 index 0000000..d684510 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py new file mode 100644 index 0000000..5aba5b5 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py new file mode 100644 index 0000000..2c8ca84 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py new file mode 100644 index 0000000..1fde48a --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py new file mode 100644 index 0000000..abc8ad3 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_UndeleteFolder_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_undelete_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_UndeleteFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py new file mode 100644 index 0000000..6977800 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_UndeleteFolder_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_undelete_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteFolderRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_UndeleteFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py new file mode 100644 index 0000000..515f4ae --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_UpdateFolder_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_update_folder(): + # Create a client + client = resourcemanager_v3.FoldersAsyncClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.UpdateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.update_folder(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_UpdateFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py new file mode 100644 index 0000000..c2b5f39 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFolder +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Folders_UpdateFolder_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_update_folder(): + # Create a client + client = resourcemanager_v3.FoldersClient() + + # Initialize request argument(s) + folder = resourcemanager_v3.Folder() + folder.parent = "parent_value" + + request = resourcemanager_v3.UpdateFolderRequest( + folder=folder, + ) + + # Make the request + operation = client.update_folder(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Folders_UpdateFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py new file mode 100644 index 0000000..a6fff7f --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py new file mode 100644 index 0000000..423b614 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py new file mode 100644 index 0000000..55de2b6 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOrganization +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_GetOrganization_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_get_organization(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetOrganizationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_organization(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_GetOrganization_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py new file mode 100644 index 0000000..aff37ad --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOrganization +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_GetOrganization_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_get_organization(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetOrganizationRequest( + name="name_value", + ) + + # Make the request + response = client.get_organization(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_GetOrganization_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py new file mode 100644 index 0000000..45db889 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchOrganizations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_search_organizations(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchOrganizationsRequest( + ) + + # Make the request + page_result = client.search_organizations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py new file mode 100644 index 0000000..2481a0f --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchOrganizations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_search_organizations(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchOrganizationsRequest( + ) + + # Make the request + page_result = client.search_organizations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py new file mode 100644 index 0000000..650e62a --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py new file mode 100644 index 0000000..79c73a8 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py new file mode 100644 index 0000000..423d181 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.OrganizationsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py new file mode 100644 index 0000000..c0f6aa1 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.OrganizationsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py new file mode 100644 index 0000000..0a6c6b8 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_CreateProject_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_create_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateProjectRequest( + ) + + # Make the request + operation = client.create_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_CreateProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py new file mode 100644 index 0000000..ccb70b8 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_CreateProject_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_create_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateProjectRequest( + ) + + # Make the request + operation = client.create_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_CreateProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py new file mode 100644 index 0000000..dc6bb6c --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_DeleteProject_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_delete_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_DeleteProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py new file mode 100644 index 0000000..fe6641a --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_DeleteProject_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_delete_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_DeleteProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py new file mode 100644 index 0000000..8f0a502 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py new file mode 100644 index 0000000..67b2186 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py new file mode 100644 index 0000000..bc2885e --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_GetProject_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_get_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetProjectRequest( + name="name_value", + ) + + # Make the request + response = await client.get_project(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_GetProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py new file mode 100644 index 0000000..4d5dc0b --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_GetProject_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_get_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetProjectRequest( + name="name_value", + ) + + # Make the request + response = client.get_project(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_GetProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py new file mode 100644 index 0000000..91c495f --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProjects +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_ListProjects_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_list_projects(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListProjectsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_projects(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_ListProjects_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py new file mode 100644 index 0000000..09d9898 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProjects +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_ListProjects_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_list_projects(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListProjectsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_projects(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_ListProjects_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py new file mode 100644 index 0000000..ecdd64e --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_MoveProject_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_move_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveProjectRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_MoveProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py new file mode 100644 index 0000000..37cc2cd --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MoveProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_MoveProject_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_move_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.MoveProjectRequest( + name="name_value", + destination_parent="destination_parent_value", + ) + + # Make the request + operation = client.move_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_MoveProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py new file mode 100644 index 0000000..faa6502 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchProjects +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_SearchProjects_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_search_projects(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchProjectsRequest( + ) + + # Make the request + page_result = client.search_projects(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_SearchProjects_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py new file mode 100644 index 0000000..a870908 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchProjects +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_SearchProjects_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_search_projects(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.SearchProjectsRequest( + ) + + # Make the request + page_result = client.search_projects(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_SearchProjects_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py new file mode 100644 index 0000000..d48466b --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py new file mode 100644 index 0000000..4ca4a00 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py new file mode 100644 index 0000000..e0261b7 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py new file mode 100644 index 0000000..96d142d --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py new file mode 100644 index 0000000..c818309 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_UndeleteProject_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_undelete_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_UndeleteProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py new file mode 100644 index 0000000..2961e89 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_UndeleteProject_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_undelete_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UndeleteProjectRequest( + name="name_value", + ) + + # Make the request + operation = client.undelete_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_UndeleteProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py new file mode 100644 index 0000000..cd9022e --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_UpdateProject_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_update_project(): + # Create a client + client = resourcemanager_v3.ProjectsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UpdateProjectRequest( + ) + + # Make the request + operation = client.update_project(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_UpdateProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py new file mode 100644 index 0000000..1e19ce8 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProject +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_Projects_UpdateProject_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_update_project(): + # Create a client + client = resourcemanager_v3.ProjectsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.UpdateProjectRequest( + ) + + # Make the request + operation = client.update_project(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_Projects_UpdateProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py new file mode 100644 index 0000000..18b7eb5 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTagBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_create_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateTagBindingRequest( + ) + + # Make the request + operation = client.create_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py new file mode 100644 index 0000000..764063f --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTagBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_create_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.CreateTagBindingRequest( + ) + + # Make the request + operation = client.create_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py new file mode 100644 index 0000000..a05a128 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTagBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_delete_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py new file mode 100644 index 0000000..2ae22e1 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTagBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_delete_tag_binding(): + # Create a client + client = resourcemanager_v3.TagBindingsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py new file mode 100644 index 0000000..cf2ed15 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTagBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_list_tag_bindings(): + # Create a client + client = resourcemanager_v3.TagBindingsAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py new file mode 100644 index 0000000..0b4a750 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTagBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_list_tag_bindings(): + # Create a client + client = resourcemanager_v3.TagBindingsClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py new file mode 100644 index 0000000..780cbed --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_create_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.create_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py new file mode 100644 index 0000000..ae9a49b --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_create_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.create_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py new file mode 100644 index 0000000..7143771 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_delete_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagKeyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py new file mode 100644 index 0000000..3bea763 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_delete_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagKeyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py new file mode 100644 index 0000000..aeb6206 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py new file mode 100644 index 0000000..7cbb915 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py new file mode 100644 index 0000000..8121728 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_get_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tag_key(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py new file mode 100644 index 0000000..3228ea3 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_get_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_tag_key(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py new file mode 100644 index 0000000..922511e --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTagKeys +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_list_tag_keys(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_keys(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py new file mode 100644 index 0000000..6ee7f60 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTagKeys +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_list_tag_keys(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_keys(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py new file mode 100644 index 0000000..bd2f51c --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py new file mode 100644 index 0000000..9d9e820 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py new file mode 100644 index 0000000..12ace3e --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py new file mode 100644 index 0000000..a317572 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py new file mode 100644 index 0000000..0eb21f1 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_update_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysAsyncClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.update_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py new file mode 100644 index 0000000..b8f05c9 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTagKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_update_tag_key(): + # Create a client + client = resourcemanager_v3.TagKeysClient() + + # Initialize request argument(s) + tag_key = resourcemanager_v3.TagKey() + tag_key.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagKeyRequest( + tag_key=tag_key, + ) + + # Make the request + operation = client.update_tag_key(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py new file mode 100644 index 0000000..646f938 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_CreateTagValue_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_create_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.create_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_CreateTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py new file mode 100644 index 0000000..2ca20b7 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_CreateTagValue_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_create_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.CreateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.create_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_CreateTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py new file mode 100644 index 0000000..2f9b8ad --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_delete_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagValueRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py new file mode 100644 index 0000000..e7f6a23 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_delete_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = resourcemanager_v3.DeleteTagValueRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py new file mode 100644 index 0000000..1f05b73 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py new file mode 100644 index 0000000..0a345a3 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py new file mode 100644 index 0000000..473529c --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_GetTagValue_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_get_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagValueRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tag_value(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_GetTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py new file mode 100644 index 0000000..67eabb2 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_GetTagValue_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_get_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = resourcemanager_v3.GetTagValueRequest( + name="name_value", + ) + + # Make the request + response = client.get_tag_value(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_GetTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py new file mode 100644 index 0000000..2436e0b --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTagValues +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_ListTagValues_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_list_tag_values(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagValuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_values(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_ListTagValues_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py new file mode 100644 index 0000000..0af2907 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTagValues +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_ListTagValues_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_list_tag_values(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = resourcemanager_v3.ListTagValuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tag_values(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_ListTagValues_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py new file mode 100644 index 0000000..385ccfe --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py new file mode 100644 index 0000000..77abd02 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py new file mode 100644 index 0000000..67e7083 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py new file mode 100644 index 0000000..509c9b6 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py new file mode 100644 index 0000000..d75bcf2 --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +async def sample_update_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesAsyncClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.update_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py new file mode 100644 index 0000000..b04b40a --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTagValue +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-resource-manager + + +# [START cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import resourcemanager_v3 + + +def sample_update_tag_value(): + # Create a client + client = resourcemanager_v3.TagValuesClient() + + # Initialize request argument(s) + tag_value = resourcemanager_v3.TagValue() + tag_value.short_name = "short_name_value" + + request = resourcemanager_v3.UpdateTagValueRequest( + tag_value=tag_value, + ) + + # Make the request + operation = client.update_tag_value(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json b/owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json new file mode 100644 index 0000000..bd24c8e --- /dev/null +++ b/owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json @@ -0,0 +1,7509 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.resourcemanager.v3", + "version": "v3" + } + ], + "language": "PYTHON", + "name": "google-cloud-resource-manager", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.create_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.CreateFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "CreateFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateFolderRequest" + }, + { + "name": "folder", + "type": "google.cloud.resourcemanager_v3.types.Folder" + }, + { + "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_folder" + }, + "description": "Sample for CreateFolder", + "file": "cloudresourcemanager_v3_generated_folders_create_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_CreateFolder_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_create_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.create_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.CreateFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "CreateFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateFolderRequest" + }, + { + "name": "folder", + "type": "google.cloud.resourcemanager_v3.types.Folder" + }, + { + "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_folder" + }, + "description": "Sample for CreateFolder", + "file": "cloudresourcemanager_v3_generated_folders_create_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_CreateFolder_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_create_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.delete_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.DeleteFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "DeleteFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteFolderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_folder" + }, + "description": "Sample for DeleteFolder", + "file": "cloudresourcemanager_v3_generated_folders_delete_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_DeleteFolder_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_delete_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.delete_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.DeleteFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "DeleteFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteFolderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_folder" + }, + "description": "Sample for DeleteFolder", + "file": "cloudresourcemanager_v3_generated_folders_delete_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_DeleteFolder_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_delete_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.get_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.GetFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "GetFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetFolderRequest" + }, + { + "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.resourcemanager_v3.types.Folder", + "shortName": "get_folder" + }, + "description": "Sample for GetFolder", + "file": "cloudresourcemanager_v3_generated_folders_get_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_GetFolder_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": "cloudresourcemanager_v3_generated_folders_get_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.get_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.GetFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "GetFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetFolderRequest" + }, + { + "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.resourcemanager_v3.types.Folder", + "shortName": "get_folder" + }, + "description": "Sample for GetFolder", + "file": "cloudresourcemanager_v3_generated_folders_get_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_GetFolder_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": "cloudresourcemanager_v3_generated_folders_get_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.list_folders", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.ListFolders", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "ListFolders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListFoldersRequest" + }, + { + "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.resourcemanager_v3.services.folders.pagers.ListFoldersAsyncPager", + "shortName": "list_folders" + }, + "description": "Sample for ListFolders", + "file": "cloudresourcemanager_v3_generated_folders_list_folders_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_ListFolders_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": "cloudresourcemanager_v3_generated_folders_list_folders_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.list_folders", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.ListFolders", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "ListFolders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListFoldersRequest" + }, + { + "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.resourcemanager_v3.services.folders.pagers.ListFoldersPager", + "shortName": "list_folders" + }, + "description": "Sample for ListFolders", + "file": "cloudresourcemanager_v3_generated_folders_list_folders_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_ListFolders_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": "cloudresourcemanager_v3_generated_folders_list_folders_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.move_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.MoveFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "MoveFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.MoveFolderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "destination_parent", + "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": "move_folder" + }, + "description": "Sample for MoveFolder", + "file": "cloudresourcemanager_v3_generated_folders_move_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_MoveFolder_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_move_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.move_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.MoveFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "MoveFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.MoveFolderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "destination_parent", + "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": "move_folder" + }, + "description": "Sample for MoveFolder", + "file": "cloudresourcemanager_v3_generated_folders_move_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_MoveFolder_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_move_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.search_folders", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.SearchFolders", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "SearchFolders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.SearchFoldersRequest" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersAsyncPager", + "shortName": "search_folders" + }, + "description": "Sample for SearchFolders", + "file": "cloudresourcemanager_v3_generated_folders_search_folders_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_SearchFolders_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_search_folders_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.search_folders", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.SearchFolders", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "SearchFolders" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.SearchFoldersRequest" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersPager", + "shortName": "search_folders" + }, + "description": "Sample for SearchFolders", + "file": "cloudresourcemanager_v3_generated_folders_search_folders_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_SearchFolders_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_search_folders_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.undelete_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.UndeleteFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "UndeleteFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UndeleteFolderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "undelete_folder" + }, + "description": "Sample for UndeleteFolder", + "file": "cloudresourcemanager_v3_generated_folders_undelete_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_UndeleteFolder_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_undelete_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.undelete_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.UndeleteFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "UndeleteFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UndeleteFolderRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "undelete_folder" + }, + "description": "Sample for UndeleteFolder", + "file": "cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_UndeleteFolder_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", + "shortName": "FoldersAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.update_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.UpdateFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "UpdateFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateFolderRequest" + }, + { + "name": "folder", + "type": "google.cloud.resourcemanager_v3.types.Folder" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_folder" + }, + "description": "Sample for UpdateFolder", + "file": "cloudresourcemanager_v3_generated_folders_update_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_UpdateFolder_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_update_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.FoldersClient", + "shortName": "FoldersClient" + }, + "fullName": "google.cloud.resourcemanager_v3.FoldersClient.update_folder", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Folders.UpdateFolder", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Folders", + "shortName": "Folders" + }, + "shortName": "UpdateFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateFolderRequest" + }, + { + "name": "folder", + "type": "google.cloud.resourcemanager_v3.types.Folder" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_folder" + }, + "description": "Sample for UpdateFolder", + "file": "cloudresourcemanager_v3_generated_folders_update_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Folders_UpdateFolder_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_folders_update_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", + "shortName": "OrganizationsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", + "shortName": "OrganizationsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", + "shortName": "OrganizationsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.get_organization", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.GetOrganization", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "GetOrganization" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetOrganizationRequest" + }, + { + "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.resourcemanager_v3.types.Organization", + "shortName": "get_organization" + }, + "description": "Sample for GetOrganization", + "file": "cloudresourcemanager_v3_generated_organizations_get_organization_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetOrganization_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": "cloudresourcemanager_v3_generated_organizations_get_organization_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", + "shortName": "OrganizationsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.get_organization", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.GetOrganization", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "GetOrganization" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetOrganizationRequest" + }, + { + "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.resourcemanager_v3.types.Organization", + "shortName": "get_organization" + }, + "description": "Sample for GetOrganization", + "file": "cloudresourcemanager_v3_generated_organizations_get_organization_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetOrganization_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": "cloudresourcemanager_v3_generated_organizations_get_organization_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", + "shortName": "OrganizationsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.search_organizations", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.SearchOrganizations", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "SearchOrganizations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsAsyncPager", + "shortName": "search_organizations" + }, + "description": "Sample for SearchOrganizations", + "file": "cloudresourcemanager_v3_generated_organizations_search_organizations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_search_organizations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", + "shortName": "OrganizationsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.search_organizations", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.SearchOrganizations", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "SearchOrganizations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsPager", + "shortName": "search_organizations" + }, + "description": "Sample for SearchOrganizations", + "file": "cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", + "shortName": "OrganizationsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", + "shortName": "OrganizationsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", + "shortName": "OrganizationsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", + "shortName": "OrganizationsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Organizations.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Organizations", + "shortName": "Organizations" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.create_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.CreateProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "CreateProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateProjectRequest" + }, + { + "name": "project", + "type": "google.cloud.resourcemanager_v3.types.Project" + }, + { + "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_project" + }, + "description": "Sample for CreateProject", + "file": "cloudresourcemanager_v3_generated_projects_create_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_CreateProject_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_create_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.create_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.CreateProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "CreateProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateProjectRequest" + }, + { + "name": "project", + "type": "google.cloud.resourcemanager_v3.types.Project" + }, + { + "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_project" + }, + "description": "Sample for CreateProject", + "file": "cloudresourcemanager_v3_generated_projects_create_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_CreateProject_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_create_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.delete_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.DeleteProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "DeleteProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_project" + }, + "description": "Sample for DeleteProject", + "file": "cloudresourcemanager_v3_generated_projects_delete_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_DeleteProject_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_delete_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.delete_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.DeleteProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "DeleteProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_project" + }, + "description": "Sample for DeleteProject", + "file": "cloudresourcemanager_v3_generated_projects_delete_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_DeleteProject_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_delete_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.get_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.GetProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "GetProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetProjectRequest" + }, + { + "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.resourcemanager_v3.types.Project", + "shortName": "get_project" + }, + "description": "Sample for GetProject", + "file": "cloudresourcemanager_v3_generated_projects_get_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_GetProject_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": "cloudresourcemanager_v3_generated_projects_get_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.get_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.GetProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "GetProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetProjectRequest" + }, + { + "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.resourcemanager_v3.types.Project", + "shortName": "get_project" + }, + "description": "Sample for GetProject", + "file": "cloudresourcemanager_v3_generated_projects_get_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_GetProject_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": "cloudresourcemanager_v3_generated_projects_get_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.list_projects", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.ListProjects", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "ListProjects" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListProjectsRequest" + }, + { + "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.resourcemanager_v3.services.projects.pagers.ListProjectsAsyncPager", + "shortName": "list_projects" + }, + "description": "Sample for ListProjects", + "file": "cloudresourcemanager_v3_generated_projects_list_projects_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_ListProjects_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": "cloudresourcemanager_v3_generated_projects_list_projects_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.list_projects", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.ListProjects", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "ListProjects" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListProjectsRequest" + }, + { + "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.resourcemanager_v3.services.projects.pagers.ListProjectsPager", + "shortName": "list_projects" + }, + "description": "Sample for ListProjects", + "file": "cloudresourcemanager_v3_generated_projects_list_projects_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_ListProjects_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": "cloudresourcemanager_v3_generated_projects_list_projects_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.move_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.MoveProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "MoveProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.MoveProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "destination_parent", + "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": "move_project" + }, + "description": "Sample for MoveProject", + "file": "cloudresourcemanager_v3_generated_projects_move_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_MoveProject_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_move_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.move_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.MoveProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "MoveProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.MoveProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "destination_parent", + "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": "move_project" + }, + "description": "Sample for MoveProject", + "file": "cloudresourcemanager_v3_generated_projects_move_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_MoveProject_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_move_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.search_projects", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.SearchProjects", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "SearchProjects" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.SearchProjectsRequest" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsAsyncPager", + "shortName": "search_projects" + }, + "description": "Sample for SearchProjects", + "file": "cloudresourcemanager_v3_generated_projects_search_projects_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_SearchProjects_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_search_projects_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.search_projects", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.SearchProjects", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "SearchProjects" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.SearchProjectsRequest" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsPager", + "shortName": "search_projects" + }, + "description": "Sample for SearchProjects", + "file": "cloudresourcemanager_v3_generated_projects_search_projects_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_SearchProjects_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_search_projects_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.undelete_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.UndeleteProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "UndeleteProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UndeleteProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "undelete_project" + }, + "description": "Sample for UndeleteProject", + "file": "cloudresourcemanager_v3_generated_projects_undelete_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_UndeleteProject_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_undelete_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.undelete_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.UndeleteProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "UndeleteProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UndeleteProjectRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "undelete_project" + }, + "description": "Sample for UndeleteProject", + "file": "cloudresourcemanager_v3_generated_projects_undelete_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_UndeleteProject_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_undelete_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", + "shortName": "ProjectsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.update_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.UpdateProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "UpdateProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateProjectRequest" + }, + { + "name": "project", + "type": "google.cloud.resourcemanager_v3.types.Project" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_project" + }, + "description": "Sample for UpdateProject", + "file": "cloudresourcemanager_v3_generated_projects_update_project_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_UpdateProject_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_update_project_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.update_project", + "method": { + "fullName": "google.cloud.resourcemanager.v3.Projects.UpdateProject", + "service": { + "fullName": "google.cloud.resourcemanager.v3.Projects", + "shortName": "Projects" + }, + "shortName": "UpdateProject" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateProjectRequest" + }, + { + "name": "project", + "type": "google.cloud.resourcemanager_v3.types.Project" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_project" + }, + "description": "Sample for UpdateProject", + "file": "cloudresourcemanager_v3_generated_projects_update_project_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_Projects_UpdateProject_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_projects_update_project_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient", + "shortName": "TagBindingsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient.create_tag_binding", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings.CreateTagBinding", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings", + "shortName": "TagBindings" + }, + "shortName": "CreateTagBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateTagBindingRequest" + }, + { + "name": "tag_binding", + "type": "google.cloud.resourcemanager_v3.types.TagBinding" + }, + { + "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_tag_binding" + }, + "description": "Sample for CreateTagBinding", + "file": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient", + "shortName": "TagBindingsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient.create_tag_binding", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings.CreateTagBinding", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings", + "shortName": "TagBindings" + }, + "shortName": "CreateTagBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateTagBindingRequest" + }, + { + "name": "tag_binding", + "type": "google.cloud.resourcemanager_v3.types.TagBinding" + }, + { + "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_tag_binding" + }, + "description": "Sample for CreateTagBinding", + "file": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient", + "shortName": "TagBindingsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient.delete_tag_binding", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings.DeleteTagBinding", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings", + "shortName": "TagBindings" + }, + "shortName": "DeleteTagBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_tag_binding" + }, + "description": "Sample for DeleteTagBinding", + "file": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient", + "shortName": "TagBindingsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient.delete_tag_binding", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings.DeleteTagBinding", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings", + "shortName": "TagBindings" + }, + "shortName": "DeleteTagBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_tag_binding" + }, + "description": "Sample for DeleteTagBinding", + "file": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient", + "shortName": "TagBindingsAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient.list_tag_bindings", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings.ListTagBindings", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings", + "shortName": "TagBindings" + }, + "shortName": "ListTagBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListTagBindingsRequest" + }, + { + "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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsAsyncPager", + "shortName": "list_tag_bindings" + }, + "description": "Sample for ListTagBindings", + "file": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_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": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient", + "shortName": "TagBindingsClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient.list_tag_bindings", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings.ListTagBindings", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagBindings", + "shortName": "TagBindings" + }, + "shortName": "ListTagBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListTagBindingsRequest" + }, + { + "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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsPager", + "shortName": "list_tag_bindings" + }, + "description": "Sample for ListTagBindings", + "file": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_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": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.create_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.CreateTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "CreateTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateTagKeyRequest" + }, + { + "name": "tag_key", + "type": "google.cloud.resourcemanager_v3.types.TagKey" + }, + { + "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_tag_key" + }, + "description": "Sample for CreateTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.create_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.CreateTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "CreateTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateTagKeyRequest" + }, + { + "name": "tag_key", + "type": "google.cloud.resourcemanager_v3.types.TagKey" + }, + { + "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_tag_key" + }, + "description": "Sample for CreateTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.delete_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.DeleteTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "DeleteTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_tag_key" + }, + "description": "Sample for DeleteTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.delete_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.DeleteTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "DeleteTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_tag_key" + }, + "description": "Sample for DeleteTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.get_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "GetTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetTagKeyRequest" + }, + { + "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.resourcemanager_v3.types.TagKey", + "shortName": "get_tag_key" + }, + "description": "Sample for GetTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetTagKey_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": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.get_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "GetTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetTagKeyRequest" + }, + { + "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.resourcemanager_v3.types.TagKey", + "shortName": "get_tag_key" + }, + "description": "Sample for GetTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetTagKey_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": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.list_tag_keys", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.ListTagKeys", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "ListTagKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListTagKeysRequest" + }, + { + "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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysAsyncPager", + "shortName": "list_tag_keys" + }, + "description": "Sample for ListTagKeys", + "file": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_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": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.list_tag_keys", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.ListTagKeys", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "ListTagKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListTagKeysRequest" + }, + { + "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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysPager", + "shortName": "list_tag_keys" + }, + "description": "Sample for ListTagKeys", + "file": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_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": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", + "shortName": "TagKeysAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.update_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.UpdateTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "UpdateTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest" + }, + { + "name": "tag_key", + "type": "google.cloud.resourcemanager_v3.types.TagKey" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_tag_key" + }, + "description": "Sample for UpdateTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", + "shortName": "TagKeysClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.update_tag_key", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys.UpdateTagKey", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagKeys", + "shortName": "TagKeys" + }, + "shortName": "UpdateTagKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest" + }, + { + "name": "tag_key", + "type": "google.cloud.resourcemanager_v3.types.TagKey" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_tag_key" + }, + "description": "Sample for UpdateTagKey", + "file": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.create_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.CreateTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "CreateTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateTagValueRequest" + }, + { + "name": "tag_value", + "type": "google.cloud.resourcemanager_v3.types.TagValue" + }, + { + "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_tag_value" + }, + "description": "Sample for CreateTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_CreateTagValue_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.create_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.CreateTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "CreateTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.CreateTagValueRequest" + }, + { + "name": "tag_value", + "type": "google.cloud.resourcemanager_v3.types.TagValue" + }, + { + "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_tag_value" + }, + "description": "Sample for CreateTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_CreateTagValue_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.delete_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.DeleteTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "DeleteTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteTagValueRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_tag_value" + }, + "description": "Sample for DeleteTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.delete_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.DeleteTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "DeleteTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.DeleteTagValueRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_tag_value" + }, + "description": "Sample for DeleteTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.GetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.get_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.GetTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "GetTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetTagValueRequest" + }, + { + "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.resourcemanager_v3.types.TagValue", + "shortName": "get_tag_value" + }, + "description": "Sample for GetTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetTagValue_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": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.get_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.GetTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "GetTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.GetTagValueRequest" + }, + { + "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.resourcemanager_v3.types.TagValue", + "shortName": "get_tag_value" + }, + "description": "Sample for GetTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetTagValue_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": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.list_tag_values", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.ListTagValues", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "ListTagValues" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListTagValuesRequest" + }, + { + "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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesAsyncPager", + "shortName": "list_tag_values" + }, + "description": "Sample for ListTagValues", + "file": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_ListTagValues_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": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.list_tag_values", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.ListTagValues", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "ListTagValues" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.ListTagValuesRequest" + }, + { + "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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesPager", + "shortName": "list_tag_values" + }, + "description": "Sample for ListTagValues", + "file": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_ListTagValues_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": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.set_iam_policy", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.SetIamPolicy", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.TestIamPermissions", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", + "shortName": "TagValuesAsyncClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.update_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.UpdateTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "UpdateTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateTagValueRequest" + }, + { + "name": "tag_value", + "type": "google.cloud.resourcemanager_v3.types.TagValue" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_tag_value" + }, + "description": "Sample for UpdateTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", + "shortName": "TagValuesClient" + }, + "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.update_tag_value", + "method": { + "fullName": "google.cloud.resourcemanager.v3.TagValues.UpdateTagValue", + "service": { + "fullName": "google.cloud.resourcemanager.v3.TagValues", + "shortName": "TagValues" + }, + "shortName": "UpdateTagValue" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.resourcemanager_v3.types.UpdateTagValueRequest" + }, + { + "name": "tag_value", + "type": "google.cloud.resourcemanager_v3.types.TagValue" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_tag_value" + }, + "description": "Sample for UpdateTagValue", + "file": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py" + } + ] +} diff --git a/owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py b/owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py new file mode 100644 index 0000000..da70aa8 --- /dev/null +++ b/owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py @@ -0,0 +1,209 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class resourcemanagerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_folder': ('folder', ), + 'create_project': ('project', ), + 'create_tag_binding': ('tag_binding', 'validate_only', ), + 'create_tag_key': ('tag_key', 'validate_only', ), + 'create_tag_value': ('tag_value', 'validate_only', ), + 'delete_folder': ('name', ), + 'delete_project': ('name', ), + 'delete_tag_binding': ('name', ), + 'delete_tag_key': ('name', 'validate_only', 'etag', ), + 'delete_tag_value': ('name', 'validate_only', 'etag', ), + 'get_folder': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_organization': ('name', ), + 'get_project': ('name', ), + 'get_tag_key': ('name', ), + 'get_tag_value': ('name', ), + 'list_folders': ('parent', 'page_size', 'page_token', 'show_deleted', ), + 'list_projects': ('parent', 'page_token', 'page_size', 'show_deleted', ), + 'list_tag_bindings': ('parent', 'page_size', 'page_token', ), + 'list_tag_keys': ('parent', 'page_size', 'page_token', ), + 'list_tag_values': ('parent', 'page_size', 'page_token', ), + 'move_folder': ('name', 'destination_parent', ), + 'move_project': ('name', 'destination_parent', ), + 'search_folders': ('page_size', 'page_token', 'query', ), + 'search_organizations': ('page_size', 'page_token', 'query', ), + 'search_projects': ('query', 'page_token', 'page_size', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'undelete_folder': ('name', ), + 'undelete_project': ('name', ), + 'update_folder': ('folder', 'update_mask', ), + 'update_project': ('project', 'update_mask', ), + 'update_tag_key': ('tag_key', 'update_mask', 'validate_only', ), + 'update_tag_value': ('tag_value', 'update_mask', 'validate_only', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=resourcemanagerCallTransformer(), +): + """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 resourcemanager 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/v3/setup.py b/owl-bot-staging/v3/setup.py new file mode 100644 index 0000000..47ebfe5 --- /dev/null +++ b/owl-bot-staging/v3/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-resource-manager' + + +description = "Google Cloud Resource Manager API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/resourcemanager/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/python-resource-manager" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v3/testing/constraints-3.10.txt b/owl-bot-staging/v3/testing/constraints-3.10.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v3/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/v3/testing/constraints-3.11.txt b/owl-bot-staging/v3/testing/constraints-3.11.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v3/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/v3/testing/constraints-3.12.txt b/owl-bot-staging/v3/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v3/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/v3/testing/constraints-3.7.txt b/owl-bot-staging/v3/testing/constraints-3.7.txt new file mode 100644 index 0000000..2beecf9 --- /dev/null +++ b/owl-bot-staging/v3/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v3/testing/constraints-3.8.txt b/owl-bot-staging/v3/testing/constraints-3.8.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v3/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/v3/testing/constraints-3.9.txt b/owl-bot-staging/v3/testing/constraints-3.9.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v3/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/v3/tests/__init__.py b/owl-bot-staging/v3/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v3/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v3/tests/unit/__init__.py b/owl-bot-staging/v3/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v3/tests/unit/gapic/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py new file mode 100644 index 0000000..f4ce18c --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py @@ -0,0 +1,6753 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.resourcemanager_v3.services.folders import FoldersAsyncClient +from google.cloud.resourcemanager_v3.services.folders import FoldersClient +from google.cloud.resourcemanager_v3.services.folders import pagers +from google.cloud.resourcemanager_v3.services.folders import transports +from google.cloud.resourcemanager_v3.types import folders +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 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FoldersClient._get_default_mtls_endpoint(None) is None + assert FoldersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FoldersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FoldersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FoldersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FoldersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (FoldersClient, "grpc"), + (FoldersAsyncClient, "grpc_asyncio"), + (FoldersClient, "rest"), +]) +def test_folders_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.FoldersGrpcTransport, "grpc"), + (transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.FoldersRestTransport, "rest"), +]) +def test_folders_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", [ + (FoldersClient, "grpc"), + (FoldersAsyncClient, "grpc_asyncio"), + (FoldersClient, "rest"), +]) +def test_folders_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +def test_folders_client_get_transport_class(): + transport = FoldersClient.get_transport_class() + available_transports = [ + transports.FoldersGrpcTransport, + transports.FoldersRestTransport, + ] + assert transport in available_transports + + transport = FoldersClient.get_transport_class("grpc") + assert transport == transports.FoldersGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FoldersClient, transports.FoldersGrpcTransport, "grpc"), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio"), + (FoldersClient, transports.FoldersRestTransport, "rest"), +]) +@mock.patch.object(FoldersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersClient)) +@mock.patch.object(FoldersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersAsyncClient)) +def test_folders_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(FoldersClient, '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(FoldersClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FoldersClient, transports.FoldersGrpcTransport, "grpc", "true"), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FoldersClient, transports.FoldersGrpcTransport, "grpc", "false"), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (FoldersClient, transports.FoldersRestTransport, "rest", "true"), + (FoldersClient, transports.FoldersRestTransport, "rest", "false"), +]) +@mock.patch.object(FoldersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersClient)) +@mock.patch.object(FoldersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_folders_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + FoldersClient, FoldersAsyncClient +]) +@mock.patch.object(FoldersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersClient)) +@mock.patch.object(FoldersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersAsyncClient)) +def test_folders_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FoldersClient, transports.FoldersGrpcTransport, "grpc"), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio"), + (FoldersClient, transports.FoldersRestTransport, "rest"), +]) +def test_folders_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (FoldersClient, transports.FoldersGrpcTransport, "grpc", grpc_helpers), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (FoldersClient, transports.FoldersRestTransport, "rest", None), +]) +def test_folders_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_folders_client_client_options_from_dict(): + with mock.patch('google.cloud.resourcemanager_v3.services.folders.transports.FoldersGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FoldersClient( + 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", [ + (FoldersClient, transports.FoldersGrpcTransport, "grpc", grpc_helpers), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_folders_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=None, + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + folders.GetFolderRequest, + dict, +]) +def test_get_folder(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.Folder( + name='name_value', + parent='parent_value', + display_name='display_name_value', + state=folders.Folder.State.ACTIVE, + etag='etag_value', + ) + response = client.get_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.GetFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, folders.Folder) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.state == folders.Folder.State.ACTIVE + assert response.etag == 'etag_value' + + +def test_get_folder_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_folder), + '__call__') as call: + client.get_folder() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.GetFolderRequest() + +@pytest.mark.asyncio +async def test_get_folder_async(transport: str = 'grpc_asyncio', request_type=folders.GetFolderRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(folders.Folder( + name='name_value', + parent='parent_value', + display_name='display_name_value', + state=folders.Folder.State.ACTIVE, + etag='etag_value', + )) + response = await client.get_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.GetFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, folders.Folder) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.state == folders.Folder.State.ACTIVE + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_folder_async_from_dict(): + await test_get_folder_async(request_type=dict) + + +def test_get_folder_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.GetFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_folder), + '__call__') as call: + call.return_value = folders.Folder() + client.get_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_folder_field_headers_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.GetFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_folder), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.Folder()) + await client.get_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_folder_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.Folder() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_folder( + 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_folder_flattened_error(): + client = FoldersClient( + credentials=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_folder( + folders.GetFolderRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_folder_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.Folder() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.Folder()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_folder( + 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_folder_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_folder( + folders.GetFolderRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + folders.ListFoldersRequest, + dict, +]) +def test_list_folders(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.ListFoldersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_folders(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.ListFoldersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFoldersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_folders_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_folders), + '__call__') as call: + client.list_folders() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.ListFoldersRequest() + +@pytest.mark.asyncio +async def test_list_folders_async(transport: str = 'grpc_asyncio', request_type=folders.ListFoldersRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(folders.ListFoldersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_folders(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.ListFoldersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFoldersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_folders_async_from_dict(): + await test_list_folders_async(request_type=dict) + + +def test_list_folders_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.ListFoldersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_folders( + 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_folders_flattened_error(): + client = FoldersClient( + credentials=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_folders( + folders.ListFoldersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_folders_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.ListFoldersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.ListFoldersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_folders( + 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_folders_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_folders( + folders.ListFoldersRequest(), + parent='parent_value', + ) + + +def test_list_folders_pager(transport_name: str = "grpc"): + client = FoldersClient( + 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_folders), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.ListFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_folders(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, folders.Folder) + for i in results) +def test_list_folders_pages(transport_name: str = "grpc"): + client = FoldersClient( + 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_folders), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.ListFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + pages = list(client.list_folders(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_folders_async_pager(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_folders), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.ListFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_folders(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, folders.Folder) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_folders_async_pages(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_folders), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.ListFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_folders(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + folders.SearchFoldersRequest, + dict, +]) +def test_search_folders(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.SearchFoldersResponse( + next_page_token='next_page_token_value', + ) + response = client.search_folders(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.SearchFoldersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchFoldersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_folders_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__') as call: + client.search_folders() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.SearchFoldersRequest() + +@pytest.mark.asyncio +async def test_search_folders_async(transport: str = 'grpc_asyncio', request_type=folders.SearchFoldersRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(folders.SearchFoldersResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_folders(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.SearchFoldersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchFoldersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_folders_async_from_dict(): + await test_search_folders_async(request_type=dict) + + +def test_search_folders_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.SearchFoldersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_folders( + query='query_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + + +def test_search_folders_flattened_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_folders( + folders.SearchFoldersRequest(), + query='query_value', + ) + +@pytest.mark.asyncio +async def test_search_folders_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = folders.SearchFoldersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.SearchFoldersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_folders( + query='query_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_folders_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_folders( + folders.SearchFoldersRequest(), + query='query_value', + ) + + +def test_search_folders_pager(transport_name: str = "grpc"): + client = FoldersClient( + 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.search_folders), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.SearchFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.search_folders(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, folders.Folder) + for i in results) +def test_search_folders_pages(transport_name: str = "grpc"): + client = FoldersClient( + 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.search_folders), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.SearchFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + pages = list(client.search_folders(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_search_folders_async_pager(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.SearchFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_folders(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, folders.Folder) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_folders_async_pages(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_folders), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.SearchFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_folders(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + folders.CreateFolderRequest, + dict, +]) +def test_create_folder(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.CreateFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_folder_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_folder), + '__call__') as call: + client.create_folder() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.CreateFolderRequest() + +@pytest.mark.asyncio +async def test_create_folder_async(transport: str = 'grpc_asyncio', request_type=folders.CreateFolderRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folder), + '__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_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.CreateFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_folder_async_from_dict(): + await test_create_folder_async(request_type=dict) + + +def test_create_folder_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_folder), + '__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_folder( + folder=folders.Folder(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].folder + mock_val = folders.Folder(name='name_value') + assert arg == mock_val + + +def test_create_folder_flattened_error(): + client = FoldersClient( + credentials=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_folder( + folders.CreateFolderRequest(), + folder=folders.Folder(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_folder_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_folder), + '__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_folder( + folder=folders.Folder(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].folder + mock_val = folders.Folder(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_folder_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_folder( + folders.CreateFolderRequest(), + folder=folders.Folder(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + folders.UpdateFolderRequest, + dict, +]) +def test_update_folder(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.UpdateFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_folder_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_folder), + '__call__') as call: + client.update_folder() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.UpdateFolderRequest() + +@pytest.mark.asyncio +async def test_update_folder_async(transport: str = 'grpc_asyncio', request_type=folders.UpdateFolderRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.UpdateFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_folder_async_from_dict(): + await test_update_folder_async(request_type=dict) + + +def test_update_folder_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.UpdateFolderRequest() + + request.folder.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_folder), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'folder.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_folder_field_headers_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.UpdateFolderRequest() + + request.folder.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_folder), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'folder.name=name_value', + ) in kw['metadata'] + + +def test_update_folder_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_folder( + folder=folders.Folder(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].folder + mock_val = folders.Folder(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_folder_flattened_error(): + client = FoldersClient( + credentials=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_folder( + folders.UpdateFolderRequest(), + folder=folders.Folder(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_folder_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_folder( + folder=folders.Folder(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].folder + mock_val = folders.Folder(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_folder_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_folder( + folders.UpdateFolderRequest(), + folder=folders.Folder(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + folders.MoveFolderRequest, + dict, +]) +def test_move_folder(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.move_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.MoveFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_move_folder_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__call__') as call: + client.move_folder() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.MoveFolderRequest() + +@pytest.mark.asyncio +async def test_move_folder_async(transport: str = 'grpc_asyncio', request_type=folders.MoveFolderRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__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.move_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.MoveFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_move_folder_async_from_dict(): + await test_move_folder_async(request_type=dict) + + +def test_move_folder_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.MoveFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.move_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_move_folder_field_headers_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.MoveFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.move_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_move_folder_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__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.move_folder( + name='name_value', + destination_parent='destination_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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].destination_parent + mock_val = 'destination_parent_value' + assert arg == mock_val + + +def test_move_folder_flattened_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.move_folder( + folders.MoveFolderRequest(), + name='name_value', + destination_parent='destination_parent_value', + ) + +@pytest.mark.asyncio +async def test_move_folder_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_folder), + '__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.move_folder( + name='name_value', + destination_parent='destination_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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].destination_parent + mock_val = 'destination_parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_move_folder_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.move_folder( + folders.MoveFolderRequest(), + name='name_value', + destination_parent='destination_parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + folders.DeleteFolderRequest, + dict, +]) +def test_delete_folder(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.DeleteFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_folder_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + client.delete_folder() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.DeleteFolderRequest() + +@pytest.mark.asyncio +async def test_delete_folder_async(transport: str = 'grpc_asyncio', request_type=folders.DeleteFolderRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.DeleteFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_folder_async_from_dict(): + await test_delete_folder_async(request_type=dict) + + +def test_delete_folder_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.DeleteFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_folder_field_headers_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.DeleteFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_folder_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_folder( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_folder_flattened_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_folder( + folders.DeleteFolderRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_folder_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_folder( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_folder_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_folder( + folders.DeleteFolderRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + folders.UndeleteFolderRequest, + dict, +]) +def test_undelete_folder(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undelete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == folders.UndeleteFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undelete_folder_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__call__') as call: + client.undelete_folder() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == folders.UndeleteFolderRequest() + +@pytest.mark.asyncio +async def test_undelete_folder_async(transport: str = 'grpc_asyncio', request_type=folders.UndeleteFolderRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__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.undelete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == folders.UndeleteFolderRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undelete_folder_async_from_dict(): + await test_undelete_folder_async(request_type=dict) + + +def test_undelete_folder_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.UndeleteFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undelete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_undelete_folder_field_headers_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = folders.UndeleteFolderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undelete_folder(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_undelete_folder_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__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.undelete_folder( + 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_undelete_folder_flattened_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_folder( + folders.UndeleteFolderRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_undelete_folder_flattened_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_folder), + '__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.undelete_folder( + 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_undelete_folder_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.undelete_folder( + folders.UndeleteFolderRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = FoldersClient( + 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() + + +def test_get_iam_policy_flattened(): + client = FoldersClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = FoldersClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = FoldersAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = FoldersClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = FoldersClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = FoldersAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = FoldersClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = FoldersClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = FoldersAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + folders.GetFolderRequest, + dict, +]) +def test_get_folder_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = folders.Folder( + name='name_value', + parent='parent_value', + display_name='display_name_value', + state=folders.Folder.State.ACTIVE, + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = folders.Folder.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_folder(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, folders.Folder) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.state == folders.Folder.State.ACTIVE + assert response.etag == 'etag_value' + + +def test_get_folder_rest_required_fields(request_type=folders.GetFolderRequest): + transport_class = transports.FoldersRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_folder._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_folder._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 = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = folders.Folder() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = folders.Folder.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_folder(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_folder_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_folder._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FoldersRestInterceptor, "post_get_folder") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_get_folder") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.GetFolderRequest.pb(folders.GetFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = folders.Folder.to_json(folders.Folder()) + + request = folders.GetFolderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = folders.Folder() + + client.get_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_folder_rest_bad_request(transport: str = 'rest', request_type=folders.GetFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_folder(request) + + +def test_get_folder_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = folders.Folder() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = folders.Folder.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_folder(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=folders/*}" % client.transport._host, args[1]) + + +def test_get_folder_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.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_folder( + folders.GetFolderRequest(), + name='name_value', + ) + + +def test_get_folder_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + folders.ListFoldersRequest, + dict, +]) +def test_list_folders_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = folders.ListFoldersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = folders.ListFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_folders(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFoldersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_folders_rest_required_fields(request_type=folders.ListFoldersRequest): + transport_class = transports.FoldersRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "parent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_folders._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "parent" in jsonified_request + assert jsonified_request["parent"] == request_init["parent"] + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_folders._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "parent", "show_deleted", )) + 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 = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = folders.ListFoldersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = folders.ListFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_folders(request) + + expected_params = [ + ( + "parent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_folders_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_folders._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", "showDeleted", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_folders_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FoldersRestInterceptor, "post_list_folders") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_list_folders") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.ListFoldersRequest.pb(folders.ListFoldersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = folders.ListFoldersResponse.to_json(folders.ListFoldersResponse()) + + request = folders.ListFoldersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = folders.ListFoldersResponse() + + client.list_folders(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_folders_rest_bad_request(transport: str = 'rest', request_type=folders.ListFoldersRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_folders(request) + + +def test_list_folders_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = folders.ListFoldersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = folders.ListFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_folders(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/folders" % client.transport._host, args[1]) + + +def test_list_folders_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.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_folders( + folders.ListFoldersRequest(), + parent='parent_value', + ) + + +def test_list_folders_rest_pager(transport: str = 'rest'): + client = FoldersClient( + 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 = ( + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.ListFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.ListFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(folders.ListFoldersResponse.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 = {} + + pager = client.list_folders(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, folders.Folder) + for i in results) + + pages = list(client.list_folders(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + folders.SearchFoldersRequest, + dict, +]) +def test_search_folders_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = folders.SearchFoldersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = folders.SearchFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_folders(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchFoldersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_folders_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FoldersRestInterceptor, "post_search_folders") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_search_folders") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.SearchFoldersRequest.pb(folders.SearchFoldersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = folders.SearchFoldersResponse.to_json(folders.SearchFoldersResponse()) + + request = folders.SearchFoldersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = folders.SearchFoldersResponse() + + client.search_folders(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_folders_rest_bad_request(transport: str = 'rest', request_type=folders.SearchFoldersRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_folders(request) + + +def test_search_folders_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = folders.SearchFoldersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + query='query_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = folders.SearchFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_folders(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/folders:search" % client.transport._host, args[1]) + + +def test_search_folders_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_folders( + folders.SearchFoldersRequest(), + query='query_value', + ) + + +def test_search_folders_rest_pager(transport: str = 'rest'): + client = FoldersClient( + 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 = ( + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + folders.Folder(), + ], + next_page_token='abc', + ), + folders.SearchFoldersResponse( + folders=[], + next_page_token='def', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + ], + next_page_token='ghi', + ), + folders.SearchFoldersResponse( + folders=[ + folders.Folder(), + folders.Folder(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(folders.SearchFoldersResponse.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 = {} + + pager = client.search_folders(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, folders.Folder) + for i in results) + + pages = list(client.search_folders(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + folders.CreateFolderRequest, + dict, +]) +def test_create_folder_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["folder"] = {'name': 'name_value', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_folder(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_folder_rest_required_fields(request_type=folders.CreateFolderRequest): + transport_class = transports.FoldersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_folder._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()).create_folder._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = FoldersClient( + 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_folder(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_folder_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_folder._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("folder", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_create_folder") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_create_folder") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.CreateFolderRequest.pb(folders.CreateFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = folders.CreateFolderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_folder_rest_bad_request(transport: str = 'rest', request_type=folders.CreateFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["folder"] = {'name': 'name_value', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_folder(request) + + +def test_create_folder_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {} + + # get truthy value for each flattened field + mock_args = dict( + folder=folders.Folder(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_folder(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/folders" % client.transport._host, args[1]) + + +def test_create_folder_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.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_folder( + folders.CreateFolderRequest(), + folder=folders.Folder(name='name_value'), + ) + + +def test_create_folder_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + folders.UpdateFolderRequest, + dict, +]) +def test_update_folder_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'folder': {'name': 'folders/sample1'}} + request_init["folder"] = {'name': 'folders/sample1', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_folder(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_folder_rest_required_fields(request_type=folders.UpdateFolderRequest): + transport_class = transports.FoldersRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_folder._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_folder._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 = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_folder(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_folder_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_folder._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("folder", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_update_folder") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_update_folder") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.UpdateFolderRequest.pb(folders.UpdateFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = folders.UpdateFolderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_folder_rest_bad_request(transport: str = 'rest', request_type=folders.UpdateFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'folder': {'name': 'folders/sample1'}} + request_init["folder"] = {'name': 'folders/sample1', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_folder(request) + + +def test_update_folder_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {'folder': {'name': 'folders/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + folder=folders.Folder(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_folder(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{folder.name=folders/*}" % client.transport._host, args[1]) + + +def test_update_folder_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.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_folder( + folders.UpdateFolderRequest(), + folder=folders.Folder(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_folder_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + folders.MoveFolderRequest, + dict, +]) +def test_move_folder_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.move_folder(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_move_folder_rest_required_fields(request_type=folders.MoveFolderRequest): + transport_class = transports.FoldersRestTransport + + request_init = {} + request_init["name"] = "" + request_init["destination_parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_folder._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["destinationParent"] = 'destination_parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_folder._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 "destinationParent" in jsonified_request + assert jsonified_request["destinationParent"] == 'destination_parent_value' + + client = FoldersClient( + 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.move_folder(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_move_folder_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.move_folder._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "destinationParent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_move_folder") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_move_folder") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.MoveFolderRequest.pb(folders.MoveFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = folders.MoveFolderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.move_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_folder_rest_bad_request(transport: str = 'rest', request_type=folders.MoveFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.move_folder(request) + + +def test_move_folder_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + destination_parent='destination_parent_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.move_folder(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=folders/*}:move" % client.transport._host, args[1]) + + +def test_move_folder_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.move_folder( + folders.MoveFolderRequest(), + name='name_value', + destination_parent='destination_parent_value', + ) + + +def test_move_folder_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + folders.DeleteFolderRequest, + dict, +]) +def test_delete_folder_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_folder(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_folder_rest_required_fields(request_type=folders.DeleteFolderRequest): + transport_class = transports.FoldersRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_folder._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_folder._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 = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_folder(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_folder_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_folder._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_delete_folder") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_delete_folder") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.DeleteFolderRequest.pb(folders.DeleteFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = folders.DeleteFolderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_folder_rest_bad_request(transport: str = 'rest', request_type=folders.DeleteFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_folder(request) + + +def test_delete_folder_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_folder(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=folders/*}" % client.transport._host, args[1]) + + +def test_delete_folder_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_folder( + folders.DeleteFolderRequest(), + name='name_value', + ) + + +def test_delete_folder_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + folders.UndeleteFolderRequest, + dict, +]) +def test_undelete_folder_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undelete_folder(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undelete_folder_rest_required_fields(request_type=folders.UndeleteFolderRequest): + transport_class = transports.FoldersRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undelete_folder._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()).undelete_folder._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 = FoldersClient( + 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.undelete_folder(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undelete_folder_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undelete_folder._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_undelete_folder") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_undelete_folder") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.UndeleteFolderRequest.pb(folders.UndeleteFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = folders.UndeleteFolderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_folder_rest_bad_request(transport: str = 'rest', request_type=folders.UndeleteFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undelete_folder(request) + + +def test_undelete_folder_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.undelete_folder(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=folders/*}:undelete" % client.transport._host, args[1]) + + +def test_undelete_folder_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_folder( + folders.UndeleteFolderRequest(), + name='name_value', + ) + + +def test_undelete_folder_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'folders/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.FoldersRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FoldersRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=folders/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'folders/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.FoldersRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FoldersRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=folders/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'folders/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.FoldersRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.FoldersRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.FoldersRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'folders/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'folders/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=folders/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FoldersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FoldersClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FoldersClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FoldersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FoldersClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FoldersGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FoldersGrpcTransport, + transports.FoldersGrpcAsyncIOTransport, + transports.FoldersRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = FoldersClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FoldersGrpcTransport, + ) + +def test_folders_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FoldersTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_folders_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.resourcemanager_v3.services.folders.transports.FoldersTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FoldersTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_folder', + 'list_folders', + 'search_folders', + 'create_folder', + 'update_folder', + 'move_folder', + 'delete_folder', + 'undelete_folder', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + 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_folders_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.resourcemanager_v3.services.folders.transports.FoldersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FoldersTransport( + 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/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +def test_folders_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.resourcemanager_v3.services.folders.transports.FoldersTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FoldersTransport() + adc.assert_called_once() + + +def test_folders_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) + FoldersClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FoldersGrpcTransport, + transports.FoldersGrpcAsyncIOTransport, + ], +) +def test_folders_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/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FoldersGrpcTransport, + transports.FoldersGrpcAsyncIOTransport, + transports.FoldersRestTransport, + ], +) +def test_folders_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.FoldersGrpcTransport, grpc_helpers), + (transports.FoldersGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_folders_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( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FoldersGrpcTransport, transports.FoldersGrpcAsyncIOTransport]) +def test_folders_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_folders_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.FoldersRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_folders_rest_lro_client(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_folders_host_no_port(transport_name): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_folders_host_with_port(transport_name): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_folders_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = FoldersClient( + credentials=creds1, + transport=transport_name, + ) + client2 = FoldersClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_folder._session + session2 = client2.transport.get_folder._session + assert session1 != session2 + session1 = client1.transport.list_folders._session + session2 = client2.transport.list_folders._session + assert session1 != session2 + session1 = client1.transport.search_folders._session + session2 = client2.transport.search_folders._session + assert session1 != session2 + session1 = client1.transport.create_folder._session + session2 = client2.transport.create_folder._session + assert session1 != session2 + session1 = client1.transport.update_folder._session + session2 = client2.transport.update_folder._session + assert session1 != session2 + session1 = client1.transport.move_folder._session + session2 = client2.transport.move_folder._session + assert session1 != session2 + session1 = client1.transport.delete_folder._session + session2 = client2.transport.delete_folder._session + assert session1 != session2 + session1 = client1.transport.undelete_folder._session + session2 = client2.transport.undelete_folder._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 +def test_folders_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FoldersGrpcTransport( + 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_folders_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FoldersGrpcAsyncIOTransport( + 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.FoldersGrpcTransport, transports.FoldersGrpcAsyncIOTransport]) +def test_folders_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.FoldersGrpcTransport, transports.FoldersGrpcAsyncIOTransport]) +def test_folders_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_folders_grpc_lro_client(): + client = FoldersClient( + 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_folders_grpc_lro_async_client(): + client = FoldersAsyncClient( + 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_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = FoldersClient.folder_path(folder) + assert expected == actual + + +def test_parse_folder_path(): + expected = { + "folder": "clam", + } + path = FoldersClient.folder_path(**expected) + + # Check that the path construction is reversible. + actual = FoldersClient.parse_folder_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FoldersClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FoldersClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FoldersClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = FoldersClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FoldersClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FoldersClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FoldersClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FoldersClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FoldersClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = FoldersClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FoldersClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FoldersClient.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 = FoldersClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FoldersClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FoldersClient.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.FoldersTransport, '_prep_wrapped_messages') as prep: + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FoldersTransport, '_prep_wrapped_messages') as prep: + transport_class = FoldersClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = FoldersAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = FoldersClient( + 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", [ + (FoldersClient, transports.FoldersGrpcTransport), + (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py new file mode 100644 index 0000000..5c90e69 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py @@ -0,0 +1,3765 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.resourcemanager_v3.services.organizations import OrganizationsAsyncClient +from google.cloud.resourcemanager_v3.services.organizations import OrganizationsClient +from google.cloud.resourcemanager_v3.services.organizations import pagers +from google.cloud.resourcemanager_v3.services.organizations import transports +from google.cloud.resourcemanager_v3.types import organizations +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.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert OrganizationsClient._get_default_mtls_endpoint(None) is None + assert OrganizationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OrganizationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OrganizationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OrganizationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OrganizationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (OrganizationsClient, "grpc"), + (OrganizationsAsyncClient, "grpc_asyncio"), + (OrganizationsClient, "rest"), +]) +def test_organizations_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.OrganizationsGrpcTransport, "grpc"), + (transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OrganizationsRestTransport, "rest"), +]) +def test_organizations_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", [ + (OrganizationsClient, "grpc"), + (OrganizationsAsyncClient, "grpc_asyncio"), + (OrganizationsClient, "rest"), +]) +def test_organizations_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +def test_organizations_client_get_transport_class(): + transport = OrganizationsClient.get_transport_class() + available_transports = [ + transports.OrganizationsGrpcTransport, + transports.OrganizationsRestTransport, + ] + assert transport in available_transports + + transport = OrganizationsClient.get_transport_class("grpc") + assert transport == transports.OrganizationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc"), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio"), + (OrganizationsClient, transports.OrganizationsRestTransport, "rest"), +]) +@mock.patch.object(OrganizationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsClient)) +@mock.patch.object(OrganizationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsAsyncClient)) +def test_organizations_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(OrganizationsClient, '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(OrganizationsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", "true"), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", "false"), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (OrganizationsClient, transports.OrganizationsRestTransport, "rest", "true"), + (OrganizationsClient, transports.OrganizationsRestTransport, "rest", "false"), +]) +@mock.patch.object(OrganizationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsClient)) +@mock.patch.object(OrganizationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_organizations_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + OrganizationsClient, OrganizationsAsyncClient +]) +@mock.patch.object(OrganizationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsClient)) +@mock.patch.object(OrganizationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsAsyncClient)) +def test_organizations_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc"), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio"), + (OrganizationsClient, transports.OrganizationsRestTransport, "rest"), +]) +def test_organizations_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", grpc_helpers), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (OrganizationsClient, transports.OrganizationsRestTransport, "rest", None), +]) +def test_organizations_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_organizations_client_client_options_from_dict(): + with mock.patch('google.cloud.resourcemanager_v3.services.organizations.transports.OrganizationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OrganizationsClient( + 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", [ + (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", grpc_helpers), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_organizations_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=None, + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + organizations.GetOrganizationRequest, + dict, +]) +def test_get_organization(request_type, transport: str = 'grpc'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organizations.Organization( + name='name_value', + display_name='display_name_value', + state=organizations.Organization.State.ACTIVE, + etag='etag_value', + directory_customer_id='directory_customer_id_value', + ) + response = client.get_organization(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == organizations.GetOrganizationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organizations.Organization) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == organizations.Organization.State.ACTIVE + assert response.etag == 'etag_value' + + +def test_get_organization_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization), + '__call__') as call: + client.get_organization() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == organizations.GetOrganizationRequest() + +@pytest.mark.asyncio +async def test_get_organization_async(transport: str = 'grpc_asyncio', request_type=organizations.GetOrganizationRequest): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_organization), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organizations.Organization( + name='name_value', + display_name='display_name_value', + state=organizations.Organization.State.ACTIVE, + etag='etag_value', + )) + response = await client.get_organization(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == organizations.GetOrganizationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organizations.Organization) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == organizations.Organization.State.ACTIVE + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_organization_async_from_dict(): + await test_get_organization_async(request_type=dict) + + +def test_get_organization_field_headers(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = organizations.GetOrganizationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization), + '__call__') as call: + call.return_value = organizations.Organization() + client.get_organization(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_organization_field_headers_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = organizations.GetOrganizationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organizations.Organization()) + await client.get_organization(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_organization_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organizations.Organization() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization( + 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_organization_flattened_error(): + client = OrganizationsClient( + credentials=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_organization( + organizations.GetOrganizationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_organization_flattened_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organizations.Organization() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organizations.Organization()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization( + 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_organization_flattened_error_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_organization( + organizations.GetOrganizationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + organizations.SearchOrganizationsRequest, + dict, +]) +def test_search_organizations(request_type, transport: str = 'grpc'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organizations.SearchOrganizationsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_organizations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == organizations.SearchOrganizationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchOrganizationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_organizations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__') as call: + client.search_organizations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == organizations.SearchOrganizationsRequest() + +@pytest.mark.asyncio +async def test_search_organizations_async(transport: str = 'grpc_asyncio', request_type=organizations.SearchOrganizationsRequest): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organizations.SearchOrganizationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_organizations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == organizations.SearchOrganizationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchOrganizationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_organizations_async_from_dict(): + await test_search_organizations_async(request_type=dict) + + +def test_search_organizations_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organizations.SearchOrganizationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_organizations( + query='query_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + + +def test_search_organizations_flattened_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_organizations( + organizations.SearchOrganizationsRequest(), + query='query_value', + ) + +@pytest.mark.asyncio +async def test_search_organizations_flattened_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organizations.SearchOrganizationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organizations.SearchOrganizationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_organizations( + query='query_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_organizations_flattened_error_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_organizations( + organizations.SearchOrganizationsRequest(), + query='query_value', + ) + + +def test_search_organizations_pager(transport_name: str = "grpc"): + client = OrganizationsClient( + 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.search_organizations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + organizations.Organization(), + ], + next_page_token='abc', + ), + organizations.SearchOrganizationsResponse( + organizations=[], + next_page_token='def', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + ], + next_page_token='ghi', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.search_organizations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, organizations.Organization) + for i in results) +def test_search_organizations_pages(transport_name: str = "grpc"): + client = OrganizationsClient( + 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.search_organizations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + organizations.Organization(), + ], + next_page_token='abc', + ), + organizations.SearchOrganizationsResponse( + organizations=[], + next_page_token='def', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + ], + next_page_token='ghi', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + ], + ), + RuntimeError, + ) + pages = list(client.search_organizations(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_search_organizations_async_pager(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + organizations.Organization(), + ], + next_page_token='abc', + ), + organizations.SearchOrganizationsResponse( + organizations=[], + next_page_token='def', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + ], + next_page_token='ghi', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_organizations(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, organizations.Organization) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_organizations_async_pages(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + organizations.Organization(), + ], + next_page_token='abc', + ), + organizations.SearchOrganizationsResponse( + organizations=[], + next_page_token='def', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + ], + next_page_token='ghi', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_organizations(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = OrganizationsClient( + 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() + + +def test_get_iam_policy_flattened(): + client = OrganizationsClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = OrganizationsClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = OrganizationsAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = OrganizationsClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = OrganizationsClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = OrganizationsAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = OrganizationsClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = OrganizationsClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = OrganizationsAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + organizations.GetOrganizationRequest, + dict, +]) +def test_get_organization_rest(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/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 = organizations.Organization( + name='name_value', + display_name='display_name_value', + state=organizations.Organization.State.ACTIVE, + etag='etag_value', + directory_customer_id='directory_customer_id_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = organizations.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_organization(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organizations.Organization) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.state == organizations.Organization.State.ACTIVE + assert response.etag == 'etag_value' + + +def test_get_organization_rest_required_fields(request_type=organizations.GetOrganizationRequest): + transport_class = transports.OrganizationsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_organization._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_organization._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 = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = organizations.Organization() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = organizations.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_organization(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_organization_rest_unset_required_fields(): + transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_organization._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "post_get_organization") as post, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "pre_get_organization") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = organizations.GetOrganizationRequest.pb(organizations.GetOrganizationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organizations.Organization.to_json(organizations.Organization()) + + request = organizations.GetOrganizationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organizations.Organization() + + client.get_organization(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_organization_rest_bad_request(transport: str = 'rest', request_type=organizations.GetOrganizationRequest): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_organization(request) + + +def test_get_organization_rest_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organizations.Organization() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = organizations.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_organization(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=organizations/*}" % client.transport._host, args[1]) + + +def test_get_organization_rest_flattened_error(transport: str = 'rest'): + client = OrganizationsClient( + credentials=ga_credentials.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_organization( + organizations.GetOrganizationRequest(), + name='name_value', + ) + + +def test_get_organization_rest_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + organizations.SearchOrganizationsRequest, + dict, +]) +def test_search_organizations_rest(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organizations.SearchOrganizationsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = organizations.SearchOrganizationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_organizations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchOrganizationsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_organizations_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "post_search_organizations") as post, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "pre_search_organizations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = organizations.SearchOrganizationsRequest.pb(organizations.SearchOrganizationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = organizations.SearchOrganizationsResponse.to_json(organizations.SearchOrganizationsResponse()) + + request = organizations.SearchOrganizationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organizations.SearchOrganizationsResponse() + + client.search_organizations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_organizations_rest_bad_request(transport: str = 'rest', request_type=organizations.SearchOrganizationsRequest): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_organizations(request) + + +def test_search_organizations_rest_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = organizations.SearchOrganizationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + query='query_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = organizations.SearchOrganizationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_organizations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/organizations:search" % client.transport._host, args[1]) + + +def test_search_organizations_rest_flattened_error(transport: str = 'rest'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_organizations( + organizations.SearchOrganizationsRequest(), + query='query_value', + ) + + +def test_search_organizations_rest_pager(transport: str = 'rest'): + client = OrganizationsClient( + 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 = ( + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + organizations.Organization(), + ], + next_page_token='abc', + ), + organizations.SearchOrganizationsResponse( + organizations=[], + next_page_token='def', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + ], + next_page_token='ghi', + ), + organizations.SearchOrganizationsResponse( + organizations=[ + organizations.Organization(), + organizations.Organization(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(organizations.SearchOrganizationsResponse.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 = {} + + pager = client.search_organizations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, organizations.Organization) + for i in results) + + pages = list(client.search_organizations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.OrganizationsRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=organizations/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = OrganizationsClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.OrganizationsRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=organizations/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.OrganizationsRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.OrganizationsRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'organizations/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=organizations/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OrganizationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OrganizationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OrganizationsGrpcTransport, + transports.OrganizationsGrpcAsyncIOTransport, + transports.OrganizationsRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = OrganizationsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OrganizationsGrpcTransport, + ) + +def test_organizations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OrganizationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_organizations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.resourcemanager_v3.services.organizations.transports.OrganizationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OrganizationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_organization', + 'search_organizations', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + 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_organizations_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.resourcemanager_v3.services.organizations.transports.OrganizationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationsTransport( + 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/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +def test_organizations_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.resourcemanager_v3.services.organizations.transports.OrganizationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationsTransport() + adc.assert_called_once() + + +def test_organizations_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) + OrganizationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationsGrpcTransport, + transports.OrganizationsGrpcAsyncIOTransport, + ], +) +def test_organizations_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/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationsGrpcTransport, + transports.OrganizationsGrpcAsyncIOTransport, + transports.OrganizationsRestTransport, + ], +) +def test_organizations_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.OrganizationsGrpcTransport, grpc_helpers), + (transports.OrganizationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_organizations_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( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.OrganizationsGrpcTransport, transports.OrganizationsGrpcAsyncIOTransport]) +def test_organizations_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_organizations_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.OrganizationsRestTransport ( + 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_organizations_host_no_port(transport_name): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_organizations_host_with_port(transport_name): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_organizations_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OrganizationsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OrganizationsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_organization._session + session2 = client2.transport.get_organization._session + assert session1 != session2 + session1 = client1.transport.search_organizations._session + session2 = client2.transport.search_organizations._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 +def test_organizations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OrganizationsGrpcTransport( + 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_organizations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OrganizationsGrpcAsyncIOTransport( + 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.OrganizationsGrpcTransport, transports.OrganizationsGrpcAsyncIOTransport]) +def test_organizations_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.OrganizationsGrpcTransport, transports.OrganizationsGrpcAsyncIOTransport]) +def test_organizations_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_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OrganizationsClient.organization_path(organization) + assert expected == actual + + +def test_parse_organization_path(): + expected = { + "organization": "clam", + } + path = OrganizationsClient.organization_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationsClient.parse_organization_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OrganizationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = OrganizationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = OrganizationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = OrganizationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OrganizationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = OrganizationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = OrganizationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = OrganizationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationsClient.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 = OrganizationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = OrganizationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationsClient.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.OrganizationsTransport, '_prep_wrapped_messages') as prep: + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OrganizationsTransport, '_prep_wrapped_messages') as prep: + transport_class = OrganizationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = OrganizationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = OrganizationsClient( + 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", [ + (OrganizationsClient, transports.OrganizationsGrpcTransport), + (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py new file mode 100644 index 0000000..a1e8b03 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py @@ -0,0 +1,6759 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.resourcemanager_v3.services.projects import ProjectsAsyncClient +from google.cloud.resourcemanager_v3.services.projects import ProjectsClient +from google.cloud.resourcemanager_v3.services.projects import pagers +from google.cloud.resourcemanager_v3.services.projects import transports +from google.cloud.resourcemanager_v3.types import projects +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 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProjectsClient._get_default_mtls_endpoint(None) is None + assert ProjectsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProjectsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProjectsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProjectsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProjectsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProjectsClient, "grpc"), + (ProjectsAsyncClient, "grpc_asyncio"), + (ProjectsClient, "rest"), +]) +def test_projects_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProjectsGrpcTransport, "grpc"), + (transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProjectsRestTransport, "rest"), +]) +def test_projects_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", [ + (ProjectsClient, "grpc"), + (ProjectsAsyncClient, "grpc_asyncio"), + (ProjectsClient, "rest"), +]) +def test_projects_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +def test_projects_client_get_transport_class(): + transport = ProjectsClient.get_transport_class() + available_transports = [ + transports.ProjectsGrpcTransport, + transports.ProjectsRestTransport, + ] + assert transport in available_transports + + transport = ProjectsClient.get_transport_class("grpc") + assert transport == transports.ProjectsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProjectsClient, transports.ProjectsGrpcTransport, "grpc"), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio"), + (ProjectsClient, transports.ProjectsRestTransport, "rest"), +]) +@mock.patch.object(ProjectsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsClient)) +@mock.patch.object(ProjectsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsAsyncClient)) +def test_projects_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(ProjectsClient, '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(ProjectsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", "true"), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", "false"), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProjectsClient, transports.ProjectsRestTransport, "rest", "true"), + (ProjectsClient, transports.ProjectsRestTransport, "rest", "false"), +]) +@mock.patch.object(ProjectsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsClient)) +@mock.patch.object(ProjectsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_projects_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProjectsClient, ProjectsAsyncClient +]) +@mock.patch.object(ProjectsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsClient)) +@mock.patch.object(ProjectsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsAsyncClient)) +def test_projects_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProjectsClient, transports.ProjectsGrpcTransport, "grpc"), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio"), + (ProjectsClient, transports.ProjectsRestTransport, "rest"), +]) +def test_projects_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", grpc_helpers), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProjectsClient, transports.ProjectsRestTransport, "rest", None), +]) +def test_projects_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_projects_client_client_options_from_dict(): + with mock.patch('google.cloud.resourcemanager_v3.services.projects.transports.ProjectsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProjectsClient( + 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", [ + (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", grpc_helpers), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_projects_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=None, + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + projects.GetProjectRequest, + dict, +]) +def test_get_project(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.Project( + name='name_value', + parent='parent_value', + project_id='project_id_value', + state=projects.Project.State.ACTIVE, + display_name='display_name_value', + etag='etag_value', + ) + response = client.get_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.GetProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, projects.Project) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.project_id == 'project_id_value' + assert response.state == projects.Project.State.ACTIVE + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +def test_get_project_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_project), + '__call__') as call: + client.get_project() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.GetProjectRequest() + +@pytest.mark.asyncio +async def test_get_project_async(transport: str = 'grpc_asyncio', request_type=projects.GetProjectRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(projects.Project( + name='name_value', + parent='parent_value', + project_id='project_id_value', + state=projects.Project.State.ACTIVE, + display_name='display_name_value', + etag='etag_value', + )) + response = await client.get_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.GetProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, projects.Project) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.project_id == 'project_id_value' + assert response.state == projects.Project.State.ACTIVE + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_project_async_from_dict(): + await test_get_project_async(request_type=dict) + + +def test_get_project_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.GetProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_project), + '__call__') as call: + call.return_value = projects.Project() + client.get_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_project_field_headers_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.GetProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_project), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.Project()) + await client.get_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_project_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.Project() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_project( + 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_project_flattened_error(): + client = ProjectsClient( + credentials=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_project( + projects.GetProjectRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_project_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.Project() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.Project()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_project( + 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_project_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_project( + projects.GetProjectRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + projects.ListProjectsRequest, + dict, +]) +def test_list_projects(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.ListProjectsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_projects(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.ListProjectsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProjectsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_projects_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_projects), + '__call__') as call: + client.list_projects() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.ListProjectsRequest() + +@pytest.mark.asyncio +async def test_list_projects_async(transport: str = 'grpc_asyncio', request_type=projects.ListProjectsRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(projects.ListProjectsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_projects(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.ListProjectsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProjectsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_projects_async_from_dict(): + await test_list_projects_async(request_type=dict) + + +def test_list_projects_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.ListProjectsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_projects( + 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_projects_flattened_error(): + client = ProjectsClient( + credentials=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_projects( + projects.ListProjectsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_projects_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.ListProjectsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.ListProjectsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_projects( + 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_projects_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_projects( + projects.ListProjectsRequest(), + parent='parent_value', + ) + + +def test_list_projects_pager(transport_name: str = "grpc"): + client = ProjectsClient( + 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_projects), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.ListProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_projects(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, projects.Project) + for i in results) +def test_list_projects_pages(transport_name: str = "grpc"): + client = ProjectsClient( + 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_projects), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.ListProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + pages = list(client.list_projects(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_projects_async_pager(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_projects), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.ListProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_projects(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, projects.Project) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_projects_async_pages(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_projects), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.ListProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_projects(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + projects.SearchProjectsRequest, + dict, +]) +def test_search_projects(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.SearchProjectsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_projects(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.SearchProjectsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchProjectsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_projects_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__') as call: + client.search_projects() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.SearchProjectsRequest() + +@pytest.mark.asyncio +async def test_search_projects_async(transport: str = 'grpc_asyncio', request_type=projects.SearchProjectsRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(projects.SearchProjectsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_projects(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.SearchProjectsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchProjectsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_projects_async_from_dict(): + await test_search_projects_async(request_type=dict) + + +def test_search_projects_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.SearchProjectsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_projects( + query='query_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + + +def test_search_projects_flattened_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_projects( + projects.SearchProjectsRequest(), + query='query_value', + ) + +@pytest.mark.asyncio +async def test_search_projects_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = projects.SearchProjectsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.SearchProjectsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_projects( + query='query_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_projects_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_projects( + projects.SearchProjectsRequest(), + query='query_value', + ) + + +def test_search_projects_pager(transport_name: str = "grpc"): + client = ProjectsClient( + 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.search_projects), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.SearchProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.search_projects(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, projects.Project) + for i in results) +def test_search_projects_pages(transport_name: str = "grpc"): + client = ProjectsClient( + 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.search_projects), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.SearchProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + pages = list(client.search_projects(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_search_projects_async_pager(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.SearchProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_projects(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, projects.Project) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_projects_async_pages(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_projects), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.SearchProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.search_projects(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + projects.CreateProjectRequest, + dict, +]) +def test_create_project(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.CreateProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_project_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_project), + '__call__') as call: + client.create_project() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.CreateProjectRequest() + +@pytest.mark.asyncio +async def test_create_project_async(transport: str = 'grpc_asyncio', request_type=projects.CreateProjectRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_project), + '__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_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.CreateProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_project_async_from_dict(): + await test_create_project_async(request_type=dict) + + +def test_create_project_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_project), + '__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_project( + project=projects.Project(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].project + mock_val = projects.Project(name='name_value') + assert arg == mock_val + + +def test_create_project_flattened_error(): + client = ProjectsClient( + credentials=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_project( + projects.CreateProjectRequest(), + project=projects.Project(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_project_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_project), + '__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_project( + project=projects.Project(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].project + mock_val = projects.Project(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_project_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_project( + projects.CreateProjectRequest(), + project=projects.Project(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + projects.UpdateProjectRequest, + dict, +]) +def test_update_project(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.UpdateProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_project_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_project), + '__call__') as call: + client.update_project() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.UpdateProjectRequest() + +@pytest.mark.asyncio +async def test_update_project_async(transport: str = 'grpc_asyncio', request_type=projects.UpdateProjectRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.UpdateProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_project_async_from_dict(): + await test_update_project_async(request_type=dict) + + +def test_update_project_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.UpdateProjectRequest() + + request.project.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_project), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_project_field_headers_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.UpdateProjectRequest() + + request.project.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_project), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'project.name=name_value', + ) in kw['metadata'] + + +def test_update_project_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_project( + project=projects.Project(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].project + mock_val = projects.Project(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_project_flattened_error(): + client = ProjectsClient( + credentials=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_project( + projects.UpdateProjectRequest(), + project=projects.Project(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_project_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_project( + project=projects.Project(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].project + mock_val = projects.Project(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_project_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_project( + projects.UpdateProjectRequest(), + project=projects.Project(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + projects.MoveProjectRequest, + dict, +]) +def test_move_project(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.move_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.MoveProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_move_project_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__call__') as call: + client.move_project() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.MoveProjectRequest() + +@pytest.mark.asyncio +async def test_move_project_async(transport: str = 'grpc_asyncio', request_type=projects.MoveProjectRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__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.move_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.MoveProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_move_project_async_from_dict(): + await test_move_project_async(request_type=dict) + + +def test_move_project_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.MoveProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.move_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_move_project_field_headers_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.MoveProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.move_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_move_project_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__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.move_project( + name='name_value', + destination_parent='destination_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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].destination_parent + mock_val = 'destination_parent_value' + assert arg == mock_val + + +def test_move_project_flattened_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.move_project( + projects.MoveProjectRequest(), + name='name_value', + destination_parent='destination_parent_value', + ) + +@pytest.mark.asyncio +async def test_move_project_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_project), + '__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.move_project( + name='name_value', + destination_parent='destination_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].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].destination_parent + mock_val = 'destination_parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_move_project_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.move_project( + projects.MoveProjectRequest(), + name='name_value', + destination_parent='destination_parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + projects.DeleteProjectRequest, + dict, +]) +def test_delete_project(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.DeleteProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_project_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + client.delete_project() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.DeleteProjectRequest() + +@pytest.mark.asyncio +async def test_delete_project_async(transport: str = 'grpc_asyncio', request_type=projects.DeleteProjectRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.DeleteProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_project_async_from_dict(): + await test_delete_project_async(request_type=dict) + + +def test_delete_project_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.DeleteProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_project_field_headers_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.DeleteProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_project_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_project( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_project_flattened_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_project( + projects.DeleteProjectRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_project_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_project( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_project_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_project( + projects.DeleteProjectRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + projects.UndeleteProjectRequest, + dict, +]) +def test_undelete_project(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.undelete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == projects.UndeleteProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_undelete_project_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__call__') as call: + client.undelete_project() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == projects.UndeleteProjectRequest() + +@pytest.mark.asyncio +async def test_undelete_project_async(transport: str = 'grpc_asyncio', request_type=projects.UndeleteProjectRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__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.undelete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == projects.UndeleteProjectRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_undelete_project_async_from_dict(): + await test_undelete_project_async(request_type=dict) + + +def test_undelete_project_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.UndeleteProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.undelete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_undelete_project_field_headers_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = projects.UndeleteProjectRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.undelete_project(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_undelete_project_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__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.undelete_project( + 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_undelete_project_flattened_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_project( + projects.UndeleteProjectRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_undelete_project_flattened_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_project), + '__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.undelete_project( + 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_undelete_project_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.undelete_project( + projects.UndeleteProjectRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = ProjectsClient( + 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() + + +def test_get_iam_policy_flattened(): + client = ProjectsClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = ProjectsClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = ProjectsAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = ProjectsClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = ProjectsClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = ProjectsAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = ProjectsClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = ProjectsClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = ProjectsAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + projects.GetProjectRequest, + dict, +]) +def test_get_project_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = projects.Project( + name='name_value', + parent='parent_value', + project_id='project_id_value', + state=projects.Project.State.ACTIVE, + display_name='display_name_value', + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = projects.Project.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_project(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, projects.Project) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.project_id == 'project_id_value' + assert response.state == projects.Project.State.ACTIVE + assert response.display_name == 'display_name_value' + assert response.etag == 'etag_value' + + +def test_get_project_rest_required_fields(request_type=projects.GetProjectRequest): + transport_class = transports.ProjectsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_project._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_project._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 = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = projects.Project() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = projects.Project.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_project(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_project_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_project._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProjectsRestInterceptor, "post_get_project") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_get_project") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.GetProjectRequest.pb(projects.GetProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = projects.Project.to_json(projects.Project()) + + request = projects.GetProjectRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = projects.Project() + + client.get_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_project_rest_bad_request(transport: str = 'rest', request_type=projects.GetProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_project(request) + + +def test_get_project_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = projects.Project() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = projects.Project.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_project(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=projects/*}" % client.transport._host, args[1]) + + +def test_get_project_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.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_project( + projects.GetProjectRequest(), + name='name_value', + ) + + +def test_get_project_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + projects.ListProjectsRequest, + dict, +]) +def test_list_projects_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = projects.ListProjectsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = projects.ListProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_projects(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProjectsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_projects_rest_required_fields(request_type=projects.ListProjectsRequest): + transport_class = transports.ProjectsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "parent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_projects._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "parent" in jsonified_request + assert jsonified_request["parent"] == request_init["parent"] + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_projects._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "parent", "show_deleted", )) + 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 = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = projects.ListProjectsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = projects.ListProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_projects(request) + + expected_params = [ + ( + "parent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_projects_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_projects._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", "showDeleted", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_projects_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProjectsRestInterceptor, "post_list_projects") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_list_projects") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.ListProjectsRequest.pb(projects.ListProjectsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = projects.ListProjectsResponse.to_json(projects.ListProjectsResponse()) + + request = projects.ListProjectsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = projects.ListProjectsResponse() + + client.list_projects(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_projects_rest_bad_request(transport: str = 'rest', request_type=projects.ListProjectsRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_projects(request) + + +def test_list_projects_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = projects.ListProjectsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = projects.ListProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_projects(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/projects" % client.transport._host, args[1]) + + +def test_list_projects_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.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_projects( + projects.ListProjectsRequest(), + parent='parent_value', + ) + + +def test_list_projects_rest_pager(transport: str = 'rest'): + client = ProjectsClient( + 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 = ( + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.ListProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.ListProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(projects.ListProjectsResponse.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 = {} + + pager = client.list_projects(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, projects.Project) + for i in results) + + pages = list(client.list_projects(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + projects.SearchProjectsRequest, + dict, +]) +def test_search_projects_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = projects.SearchProjectsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = projects.SearchProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_projects(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchProjectsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_projects_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProjectsRestInterceptor, "post_search_projects") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_search_projects") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.SearchProjectsRequest.pb(projects.SearchProjectsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = projects.SearchProjectsResponse.to_json(projects.SearchProjectsResponse()) + + request = projects.SearchProjectsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = projects.SearchProjectsResponse() + + client.search_projects(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_projects_rest_bad_request(transport: str = 'rest', request_type=projects.SearchProjectsRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search_projects(request) + + +def test_search_projects_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = projects.SearchProjectsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + query='query_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = projects.SearchProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_projects(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/projects:search" % client.transport._host, args[1]) + + +def test_search_projects_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_projects( + projects.SearchProjectsRequest(), + query='query_value', + ) + + +def test_search_projects_rest_pager(transport: str = 'rest'): + client = ProjectsClient( + 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 = ( + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + projects.Project(), + ], + next_page_token='abc', + ), + projects.SearchProjectsResponse( + projects=[], + next_page_token='def', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + ], + next_page_token='ghi', + ), + projects.SearchProjectsResponse( + projects=[ + projects.Project(), + projects.Project(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(projects.SearchProjectsResponse.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 = {} + + pager = client.search_projects(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, projects.Project) + for i in results) + + pages = list(client.search_projects(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + projects.CreateProjectRequest, + dict, +]) +def test_create_project_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["project"] = {'name': 'name_value', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_project(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_project_rest_required_fields(request_type=projects.CreateProjectRequest): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_project._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()).create_project._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ProjectsClient( + 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_project(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_project_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_project._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("project", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_create_project") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_create_project") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.CreateProjectRequest.pb(projects.CreateProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = projects.CreateProjectRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_project_rest_bad_request(transport: str = 'rest', request_type=projects.CreateProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["project"] = {'name': 'name_value', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_project(request) + + +def test_create_project_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {} + + # get truthy value for each flattened field + mock_args = dict( + project=projects.Project(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_project(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/projects" % client.transport._host, args[1]) + + +def test_create_project_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.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_project( + projects.CreateProjectRequest(), + project=projects.Project(name='name_value'), + ) + + +def test_create_project_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + projects.UpdateProjectRequest, + dict, +]) +def test_update_project_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'project': {'name': 'projects/sample1'}} + request_init["project"] = {'name': 'projects/sample1', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_project(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_project_rest_required_fields(request_type=projects.UpdateProjectRequest): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_project._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_project._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 = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_project(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_project_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_project._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("project", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_update_project") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_update_project") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.UpdateProjectRequest.pb(projects.UpdateProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = projects.UpdateProjectRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_project_rest_bad_request(transport: str = 'rest', request_type=projects.UpdateProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'project': {'name': 'projects/sample1'}} + request_init["project"] = {'name': 'projects/sample1', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_project(request) + + +def test_update_project_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {'project': {'name': 'projects/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + project=projects.Project(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_project(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{project.name=projects/*}" % client.transport._host, args[1]) + + +def test_update_project_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.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_project( + projects.UpdateProjectRequest(), + project=projects.Project(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_project_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + projects.MoveProjectRequest, + dict, +]) +def test_move_project_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.move_project(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_move_project_rest_required_fields(request_type=projects.MoveProjectRequest): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request_init["name"] = "" + request_init["destination_parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_project._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["destinationParent"] = 'destination_parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_project._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 "destinationParent" in jsonified_request + assert jsonified_request["destinationParent"] == 'destination_parent_value' + + client = ProjectsClient( + 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.move_project(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_move_project_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.move_project._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "destinationParent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_move_project") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_move_project") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.MoveProjectRequest.pb(projects.MoveProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = projects.MoveProjectRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.move_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_project_rest_bad_request(transport: str = 'rest', request_type=projects.MoveProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.move_project(request) + + +def test_move_project_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + destination_parent='destination_parent_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.move_project(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=projects/*}:move" % client.transport._host, args[1]) + + +def test_move_project_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.move_project( + projects.MoveProjectRequest(), + name='name_value', + destination_parent='destination_parent_value', + ) + + +def test_move_project_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + projects.DeleteProjectRequest, + dict, +]) +def test_delete_project_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_project(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_project_rest_required_fields(request_type=projects.DeleteProjectRequest): + transport_class = transports.ProjectsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_project._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_project._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 = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_project(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_project_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_project._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_delete_project") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_delete_project") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.DeleteProjectRequest.pb(projects.DeleteProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = projects.DeleteProjectRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_project_rest_bad_request(transport: str = 'rest', request_type=projects.DeleteProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_project(request) + + +def test_delete_project_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_project(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=projects/*}" % client.transport._host, args[1]) + + +def test_delete_project_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_project( + projects.DeleteProjectRequest(), + name='name_value', + ) + + +def test_delete_project_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + projects.UndeleteProjectRequest, + dict, +]) +def test_undelete_project_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.undelete_project(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undelete_project_rest_required_fields(request_type=projects.UndeleteProjectRequest): + transport_class = transports.ProjectsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undelete_project._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()).undelete_project._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 = ProjectsClient( + 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.undelete_project(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_undelete_project_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.undelete_project._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_undelete_project") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_undelete_project") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.UndeleteProjectRequest.pb(projects.UndeleteProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = projects.UndeleteProjectRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_project_rest_bad_request(transport: str = 'rest', request_type=projects.UndeleteProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undelete_project(request) + + +def test_undelete_project_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.undelete_project(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=projects/*}:undelete" % client.transport._host, args[1]) + + +def test_undelete_project_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_project( + projects.UndeleteProjectRequest(), + name='name_value', + ) + + +def test_undelete_project_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': '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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProjectsRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=projects/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': '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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProjectsRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=projects/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': '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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProjectsRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.ProjectsRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': '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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=projects/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProjectsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProjectsGrpcTransport, + transports.ProjectsGrpcAsyncIOTransport, + transports.ProjectsRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ProjectsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProjectsGrpcTransport, + ) + +def test_projects_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProjectsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_projects_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.resourcemanager_v3.services.projects.transports.ProjectsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProjectsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_project', + 'list_projects', + 'search_projects', + 'create_project', + 'update_project', + 'move_project', + 'delete_project', + 'undelete_project', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + 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_projects_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.resourcemanager_v3.services.projects.transports.ProjectsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectsTransport( + 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/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +def test_projects_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.resourcemanager_v3.services.projects.transports.ProjectsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectsTransport() + adc.assert_called_once() + + +def test_projects_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) + ProjectsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectsGrpcTransport, + transports.ProjectsGrpcAsyncIOTransport, + ], +) +def test_projects_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/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectsGrpcTransport, + transports.ProjectsGrpcAsyncIOTransport, + transports.ProjectsRestTransport, + ], +) +def test_projects_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.ProjectsGrpcTransport, grpc_helpers), + (transports.ProjectsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_projects_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( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProjectsGrpcTransport, transports.ProjectsGrpcAsyncIOTransport]) +def test_projects_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_projects_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.ProjectsRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_projects_rest_lro_client(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_projects_host_no_port(transport_name): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_projects_host_with_port(transport_name): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_projects_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProjectsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProjectsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_project._session + session2 = client2.transport.get_project._session + assert session1 != session2 + session1 = client1.transport.list_projects._session + session2 = client2.transport.list_projects._session + assert session1 != session2 + session1 = client1.transport.search_projects._session + session2 = client2.transport.search_projects._session + assert session1 != session2 + session1 = client1.transport.create_project._session + session2 = client2.transport.create_project._session + assert session1 != session2 + session1 = client1.transport.update_project._session + session2 = client2.transport.update_project._session + assert session1 != session2 + session1 = client1.transport.move_project._session + session2 = client2.transport.move_project._session + assert session1 != session2 + session1 = client1.transport.delete_project._session + session2 = client2.transport.delete_project._session + assert session1 != session2 + session1 = client1.transport.undelete_project._session + session2 = client2.transport.undelete_project._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 +def test_projects_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProjectsGrpcTransport( + 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_projects_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProjectsGrpcAsyncIOTransport( + 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.ProjectsGrpcTransport, transports.ProjectsGrpcAsyncIOTransport]) +def test_projects_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.ProjectsGrpcTransport, transports.ProjectsGrpcAsyncIOTransport]) +def test_projects_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_projects_grpc_lro_client(): + client = ProjectsClient( + 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_projects_grpc_lro_async_client(): + client = ProjectsAsyncClient( + 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_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProjectsClient.project_path(project) + assert expected == actual + + +def test_parse_project_path(): + expected = { + "project": "clam", + } + path = ProjectsClient.project_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectsClient.parse_project_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProjectsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ProjectsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProjectsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ProjectsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProjectsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ProjectsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ProjectsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ProjectsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectsClient.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 = ProjectsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ProjectsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectsClient.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.ProjectsTransport, '_prep_wrapped_messages') as prep: + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProjectsTransport, '_prep_wrapped_messages') as prep: + transport_class = ProjectsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ProjectsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ProjectsClient( + 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", [ + (ProjectsClient, transports.ProjectsGrpcTransport), + (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py new file mode 100644 index 0000000..f71883f --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py @@ -0,0 +1,2788 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.resourcemanager_v3.services.tag_bindings import TagBindingsAsyncClient +from google.cloud.resourcemanager_v3.services.tag_bindings import TagBindingsClient +from google.cloud.resourcemanager_v3.services.tag_bindings import pagers +from google.cloud.resourcemanager_v3.services.tag_bindings import transports +from google.cloud.resourcemanager_v3.types import tag_bindings +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TagBindingsClient._get_default_mtls_endpoint(None) is None + assert TagBindingsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TagBindingsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TagBindingsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TagBindingsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TagBindingsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (TagBindingsClient, "grpc"), + (TagBindingsAsyncClient, "grpc_asyncio"), + (TagBindingsClient, "rest"), +]) +def test_tag_bindings_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.TagBindingsGrpcTransport, "grpc"), + (transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TagBindingsRestTransport, "rest"), +]) +def test_tag_bindings_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", [ + (TagBindingsClient, "grpc"), + (TagBindingsAsyncClient, "grpc_asyncio"), + (TagBindingsClient, "rest"), +]) +def test_tag_bindings_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +def test_tag_bindings_client_get_transport_class(): + transport = TagBindingsClient.get_transport_class() + available_transports = [ + transports.TagBindingsGrpcTransport, + transports.TagBindingsRestTransport, + ] + assert transport in available_transports + + transport = TagBindingsClient.get_transport_class("grpc") + assert transport == transports.TagBindingsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc"), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio"), + (TagBindingsClient, transports.TagBindingsRestTransport, "rest"), +]) +@mock.patch.object(TagBindingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsClient)) +@mock.patch.object(TagBindingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsAsyncClient)) +def test_tag_bindings_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(TagBindingsClient, '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(TagBindingsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", "true"), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", "false"), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TagBindingsClient, transports.TagBindingsRestTransport, "rest", "true"), + (TagBindingsClient, transports.TagBindingsRestTransport, "rest", "false"), +]) +@mock.patch.object(TagBindingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsClient)) +@mock.patch.object(TagBindingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tag_bindings_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + TagBindingsClient, TagBindingsAsyncClient +]) +@mock.patch.object(TagBindingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsClient)) +@mock.patch.object(TagBindingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsAsyncClient)) +def test_tag_bindings_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc"), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio"), + (TagBindingsClient, transports.TagBindingsRestTransport, "rest"), +]) +def test_tag_bindings_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", grpc_helpers), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TagBindingsClient, transports.TagBindingsRestTransport, "rest", None), +]) +def test_tag_bindings_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_tag_bindings_client_client_options_from_dict(): + with mock.patch('google.cloud.resourcemanager_v3.services.tag_bindings.transports.TagBindingsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TagBindingsClient( + 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", [ + (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", grpc_helpers), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_tag_bindings_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=None, + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + tag_bindings.ListTagBindingsRequest, + dict, +]) +def test_list_tag_bindings(request_type, transport: str = 'grpc'): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_bindings.ListTagBindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tag_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.ListTagBindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagBindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tag_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), + '__call__') as call: + client.list_tag_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.ListTagBindingsRequest() + +@pytest.mark.asyncio +async def test_list_tag_bindings_async(transport: str = 'grpc_asyncio', request_type=tag_bindings.ListTagBindingsRequest): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_bindings.ListTagBindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tag_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.ListTagBindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagBindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tag_bindings_async_from_dict(): + await test_list_tag_bindings_async(request_type=dict) + + +def test_list_tag_bindings_flattened(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_bindings.ListTagBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tag_bindings( + 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_tag_bindings_flattened_error(): + client = TagBindingsClient( + credentials=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_tag_bindings( + tag_bindings.ListTagBindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_tag_bindings_flattened_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_bindings.ListTagBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_bindings.ListTagBindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tag_bindings( + 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_tag_bindings_flattened_error_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tag_bindings( + tag_bindings.ListTagBindingsRequest(), + parent='parent_value', + ) + + +def test_list_tag_bindings_pager(transport_name: str = "grpc"): + client = TagBindingsClient( + 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_tag_bindings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + next_page_token='abc', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[], + next_page_token='def', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + ], + next_page_token='ghi', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_tag_bindings(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_bindings.TagBinding) + for i in results) +def test_list_tag_bindings_pages(transport_name: str = "grpc"): + client = TagBindingsClient( + 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_tag_bindings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + next_page_token='abc', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[], + next_page_token='def', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + ], + next_page_token='ghi', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tag_bindings(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_tag_bindings_async_pager(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + next_page_token='abc', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[], + next_page_token='def', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + ], + next_page_token='ghi', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tag_bindings(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, tag_bindings.TagBinding) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_tag_bindings_async_pages(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + next_page_token='abc', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[], + next_page_token='def', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + ], + next_page_token='ghi', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_tag_bindings(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + tag_bindings.CreateTagBindingRequest, + dict, +]) +def test_create_tag_binding(request_type, transport: str = 'grpc'): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_tag_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.CreateTagBindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_tag_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_binding), + '__call__') as call: + client.create_tag_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.CreateTagBindingRequest() + +@pytest.mark.asyncio +async def test_create_tag_binding_async(transport: str = 'grpc_asyncio', request_type=tag_bindings.CreateTagBindingRequest): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_binding), + '__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_tag_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.CreateTagBindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_tag_binding_async_from_dict(): + await test_create_tag_binding_async(request_type=dict) + + +def test_create_tag_binding_flattened(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_binding), + '__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_tag_binding( + tag_binding=tag_bindings.TagBinding(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].tag_binding + mock_val = tag_bindings.TagBinding(name='name_value') + assert arg == mock_val + + +def test_create_tag_binding_flattened_error(): + client = TagBindingsClient( + credentials=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_tag_binding( + tag_bindings.CreateTagBindingRequest(), + tag_binding=tag_bindings.TagBinding(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_tag_binding_flattened_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_binding), + '__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_tag_binding( + tag_binding=tag_bindings.TagBinding(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].tag_binding + mock_val = tag_bindings.TagBinding(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_tag_binding_flattened_error_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tag_binding( + tag_bindings.CreateTagBindingRequest(), + tag_binding=tag_bindings.TagBinding(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + tag_bindings.DeleteTagBindingRequest, + dict, +]) +def test_delete_tag_binding(request_type, transport: str = 'grpc'): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_tag_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.DeleteTagBindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_tag_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + client.delete_tag_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.DeleteTagBindingRequest() + +@pytest.mark.asyncio +async def test_delete_tag_binding_async(transport: str = 'grpc_asyncio', request_type=tag_bindings.DeleteTagBindingRequest): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_tag_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_bindings.DeleteTagBindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_tag_binding_async_from_dict(): + await test_delete_tag_binding_async(request_type=dict) + + +def test_delete_tag_binding_field_headers(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_bindings.DeleteTagBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_tag_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_tag_binding_field_headers_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_bindings.DeleteTagBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_tag_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_tag_binding_flattened(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_tag_binding( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_tag_binding_flattened_error(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tag_binding( + tag_bindings.DeleteTagBindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_tag_binding_flattened_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_tag_binding( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_tag_binding_flattened_error_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tag_binding( + tag_bindings.DeleteTagBindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + tag_bindings.ListTagBindingsRequest, + dict, +]) +def test_list_tag_bindings_rest(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_bindings.ListTagBindingsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_tag_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagBindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tag_bindings_rest_required_fields(request_type=tag_bindings.ListTagBindingsRequest): + transport_class = transports.TagBindingsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "parent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "parent" in jsonified_request + assert jsonified_request["parent"] == request_init["parent"] + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "parent", )) + 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 = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tag_bindings.ListTagBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_tag_bindings(request) + + expected_params = [ + ( + "parent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_tag_bindings_rest_unset_required_fields(): + transport = transports.TagBindingsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_tag_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_bindings_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagBindingsRestInterceptor, "post_list_tag_bindings") as post, \ + mock.patch.object(transports.TagBindingsRestInterceptor, "pre_list_tag_bindings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.ListTagBindingsRequest.pb(tag_bindings.ListTagBindingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tag_bindings.ListTagBindingsResponse.to_json(tag_bindings.ListTagBindingsResponse()) + + request = tag_bindings.ListTagBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_bindings.ListTagBindingsResponse() + + client.list_tag_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tag_bindings_rest_bad_request(transport: str = 'rest', request_type=tag_bindings.ListTagBindingsRequest): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tag_bindings(request) + + +def test_list_tag_bindings_rest_flattened(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_bindings.ListTagBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_tag_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/tagBindings" % client.transport._host, args[1]) + + +def test_list_tag_bindings_rest_flattened_error(transport: str = 'rest'): + client = TagBindingsClient( + credentials=ga_credentials.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_tag_bindings( + tag_bindings.ListTagBindingsRequest(), + parent='parent_value', + ) + + +def test_list_tag_bindings_rest_pager(transport: str = 'rest'): + client = TagBindingsClient( + 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 = ( + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + next_page_token='abc', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[], + next_page_token='def', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + ], + next_page_token='ghi', + ), + tag_bindings.ListTagBindingsResponse( + tag_bindings=[ + tag_bindings.TagBinding(), + tag_bindings.TagBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tag_bindings.ListTagBindingsResponse.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 = {} + + pager = client.list_tag_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_bindings.TagBinding) + for i in results) + + pages = list(client.list_tag_bindings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + tag_bindings.CreateTagBindingRequest, + dict, +]) +def test_create_tag_binding_rest(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_binding"] = {'name': 'name_value', 'parent': 'parent_value', 'tag_value': 'tag_value_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_tag_binding(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_tag_binding_rest_required_fields(request_type=tag_bindings.CreateTagBindingRequest): + transport_class = transports.TagBindingsRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tag_binding._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()).create_tag_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = TagBindingsClient( + 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_tag_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_tag_binding_rest_unset_required_fields(): + transport = transports.TagBindingsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_tag_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", )) & set(("tagBinding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_binding_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_create_tag_binding") as post, \ + mock.patch.object(transports.TagBindingsRestInterceptor, "pre_create_tag_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.CreateTagBindingRequest.pb(tag_bindings.CreateTagBindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_bindings.CreateTagBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tag_binding_rest_bad_request(transport: str = 'rest', request_type=tag_bindings.CreateTagBindingRequest): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_binding"] = {'name': 'name_value', 'parent': 'parent_value', 'tag_value': 'tag_value_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_tag_binding(request) + + +def test_create_tag_binding_rest_flattened(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {} + + # get truthy value for each flattened field + mock_args = dict( + tag_binding=tag_bindings.TagBinding(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_tag_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/tagBindings" % client.transport._host, args[1]) + + +def test_create_tag_binding_rest_flattened_error(transport: str = 'rest'): + client = TagBindingsClient( + credentials=ga_credentials.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_tag_binding( + tag_bindings.CreateTagBindingRequest(), + tag_binding=tag_bindings.TagBinding(name='name_value'), + ) + + +def test_create_tag_binding_rest_error(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_bindings.DeleteTagBindingRequest, + dict, +]) +def test_delete_tag_binding_rest(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagBindings/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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_tag_binding(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_tag_binding_rest_required_fields(request_type=tag_bindings.DeleteTagBindingRequest): + transport_class = transports.TagBindingsRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_binding._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 = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_tag_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_tag_binding_rest_unset_required_fields(): + transport = transports.TagBindingsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_tag_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_binding_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_delete_tag_binding") as post, \ + mock.patch.object(transports.TagBindingsRestInterceptor, "pre_delete_tag_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.DeleteTagBindingRequest.pb(tag_bindings.DeleteTagBindingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_bindings.DeleteTagBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_binding_rest_bad_request(transport: str = 'rest', request_type=tag_bindings.DeleteTagBindingRequest): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagBindings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_tag_binding(request) + + +def test_delete_tag_binding_rest_flattened(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'tagBindings/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_tag_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=tagBindings/**}" % client.transport._host, args[1]) + + +def test_delete_tag_binding_rest_flattened_error(transport: str = 'rest'): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tag_binding( + tag_bindings.DeleteTagBindingRequest(), + name='name_value', + ) + + +def test_delete_tag_binding_rest_error(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagBindingsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagBindingsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TagBindingsGrpcTransport, + transports.TagBindingsGrpcAsyncIOTransport, + transports.TagBindingsRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = TagBindingsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TagBindingsGrpcTransport, + ) + +def test_tag_bindings_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TagBindingsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_tag_bindings_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.resourcemanager_v3.services.tag_bindings.transports.TagBindingsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TagBindingsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_tag_bindings', + 'create_tag_binding', + 'delete_tag_binding', + ) + 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_tag_bindings_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.resourcemanager_v3.services.tag_bindings.transports.TagBindingsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TagBindingsTransport( + 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/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +def test_tag_bindings_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.resourcemanager_v3.services.tag_bindings.transports.TagBindingsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TagBindingsTransport() + adc.assert_called_once() + + +def test_tag_bindings_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) + TagBindingsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagBindingsGrpcTransport, + transports.TagBindingsGrpcAsyncIOTransport, + ], +) +def test_tag_bindings_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/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagBindingsGrpcTransport, + transports.TagBindingsGrpcAsyncIOTransport, + transports.TagBindingsRestTransport, + ], +) +def test_tag_bindings_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.TagBindingsGrpcTransport, grpc_helpers), + (transports.TagBindingsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_tag_bindings_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( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TagBindingsGrpcTransport, transports.TagBindingsGrpcAsyncIOTransport]) +def test_tag_bindings_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_tag_bindings_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.TagBindingsRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_tag_bindings_rest_lro_client(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_tag_bindings_host_no_port(transport_name): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_tag_bindings_host_with_port(transport_name): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_tag_bindings_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TagBindingsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TagBindingsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_tag_bindings._session + session2 = client2.transport.list_tag_bindings._session + assert session1 != session2 + session1 = client1.transport.create_tag_binding._session + session2 = client2.transport.create_tag_binding._session + assert session1 != session2 + session1 = client1.transport.delete_tag_binding._session + session2 = client2.transport.delete_tag_binding._session + assert session1 != session2 +def test_tag_bindings_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TagBindingsGrpcTransport( + 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_tag_bindings_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TagBindingsGrpcAsyncIOTransport( + 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.TagBindingsGrpcTransport, transports.TagBindingsGrpcAsyncIOTransport]) +def test_tag_bindings_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.TagBindingsGrpcTransport, transports.TagBindingsGrpcAsyncIOTransport]) +def test_tag_bindings_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_tag_bindings_grpc_lro_client(): + client = TagBindingsClient( + 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_tag_bindings_grpc_lro_async_client(): + client = TagBindingsAsyncClient( + 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_tag_binding_path(): + tag_binding = "squid" + expected = "tagBindings/{tag_binding}".format(tag_binding=tag_binding, ) + actual = TagBindingsClient.tag_binding_path(tag_binding) + assert expected == actual + + +def test_parse_tag_binding_path(): + expected = { + "tag_binding": "clam", + } + path = TagBindingsClient.tag_binding_path(**expected) + + # Check that the path construction is reversible. + actual = TagBindingsClient.parse_tag_binding_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TagBindingsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = TagBindingsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TagBindingsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = TagBindingsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = TagBindingsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TagBindingsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TagBindingsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = TagBindingsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TagBindingsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = TagBindingsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = TagBindingsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TagBindingsClient.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 = TagBindingsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = TagBindingsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TagBindingsClient.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.TagBindingsTransport, '_prep_wrapped_messages') as prep: + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TagBindingsTransport, '_prep_wrapped_messages') as prep: + transport_class = TagBindingsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = TagBindingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = TagBindingsClient( + 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", [ + (TagBindingsClient, transports.TagBindingsGrpcTransport), + (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py new file mode 100644 index 0000000..83be7f1 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py @@ -0,0 +1,5257 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.resourcemanager_v3.services.tag_keys import TagKeysAsyncClient +from google.cloud.resourcemanager_v3.services.tag_keys import TagKeysClient +from google.cloud.resourcemanager_v3.services.tag_keys import pagers +from google.cloud.resourcemanager_v3.services.tag_keys import transports +from google.cloud.resourcemanager_v3.types import tag_keys +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 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TagKeysClient._get_default_mtls_endpoint(None) is None + assert TagKeysClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TagKeysClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TagKeysClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TagKeysClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TagKeysClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (TagKeysClient, "grpc"), + (TagKeysAsyncClient, "grpc_asyncio"), + (TagKeysClient, "rest"), +]) +def test_tag_keys_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.TagKeysGrpcTransport, "grpc"), + (transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TagKeysRestTransport, "rest"), +]) +def test_tag_keys_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", [ + (TagKeysClient, "grpc"), + (TagKeysAsyncClient, "grpc_asyncio"), + (TagKeysClient, "rest"), +]) +def test_tag_keys_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +def test_tag_keys_client_get_transport_class(): + transport = TagKeysClient.get_transport_class() + available_transports = [ + transports.TagKeysGrpcTransport, + transports.TagKeysRestTransport, + ] + assert transport in available_transports + + transport = TagKeysClient.get_transport_class("grpc") + assert transport == transports.TagKeysGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TagKeysClient, transports.TagKeysGrpcTransport, "grpc"), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio"), + (TagKeysClient, transports.TagKeysRestTransport, "rest"), +]) +@mock.patch.object(TagKeysClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysClient)) +@mock.patch.object(TagKeysAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysAsyncClient)) +def test_tag_keys_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(TagKeysClient, '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(TagKeysClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", "true"), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", "false"), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TagKeysClient, transports.TagKeysRestTransport, "rest", "true"), + (TagKeysClient, transports.TagKeysRestTransport, "rest", "false"), +]) +@mock.patch.object(TagKeysClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysClient)) +@mock.patch.object(TagKeysAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tag_keys_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + TagKeysClient, TagKeysAsyncClient +]) +@mock.patch.object(TagKeysClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysClient)) +@mock.patch.object(TagKeysAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysAsyncClient)) +def test_tag_keys_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TagKeysClient, transports.TagKeysGrpcTransport, "grpc"), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio"), + (TagKeysClient, transports.TagKeysRestTransport, "rest"), +]) +def test_tag_keys_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", grpc_helpers), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TagKeysClient, transports.TagKeysRestTransport, "rest", None), +]) +def test_tag_keys_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_tag_keys_client_client_options_from_dict(): + with mock.patch('google.cloud.resourcemanager_v3.services.tag_keys.transports.TagKeysGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TagKeysClient( + 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", [ + (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", grpc_helpers), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_tag_keys_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=None, + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.ListTagKeysRequest, + dict, +]) +def test_list_tag_keys(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_keys.ListTagKeysResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tag_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] == tag_keys.ListTagKeysRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagKeysPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tag_keys_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_keys), + '__call__') as call: + client.list_tag_keys() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.ListTagKeysRequest() + +@pytest.mark.asyncio +async def test_list_tag_keys_async(transport: str = 'grpc_asyncio', request_type=tag_keys.ListTagKeysRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.ListTagKeysResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tag_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.ListTagKeysRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagKeysAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tag_keys_async_from_dict(): + await test_list_tag_keys_async(request_type=dict) + + +def test_list_tag_keys_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_keys.ListTagKeysResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tag_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_tag_keys_flattened_error(): + client = TagKeysClient( + credentials=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_tag_keys( + tag_keys.ListTagKeysRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_tag_keys_flattened_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_keys.ListTagKeysResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.ListTagKeysResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tag_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_tag_keys_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tag_keys( + tag_keys.ListTagKeysRequest(), + parent='parent_value', + ) + + +def test_list_tag_keys_pager(transport_name: str = "grpc"): + client = TagKeysClient( + 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_tag_keys), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + next_page_token='abc', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[], + next_page_token='def', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + ], + next_page_token='ghi', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_tag_keys(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_keys.TagKey) + for i in results) +def test_list_tag_keys_pages(transport_name: str = "grpc"): + client = TagKeysClient( + 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_tag_keys), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + next_page_token='abc', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[], + next_page_token='def', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + ], + next_page_token='ghi', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tag_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_tag_keys_async_pager(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_keys), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + next_page_token='abc', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[], + next_page_token='def', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + ], + next_page_token='ghi', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tag_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, tag_keys.TagKey) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_tag_keys_async_pages(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_keys), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + next_page_token='abc', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[], + next_page_token='def', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + ], + next_page_token='ghi', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_tag_keys(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + tag_keys.GetTagKeyRequest, + dict, +]) +def test_get_tag_key(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_keys.TagKey( + name='name_value', + parent='parent_value', + short_name='short_name_value', + namespaced_name='namespaced_name_value', + description='description_value', + etag='etag_value', + ) + response = client.get_tag_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] == tag_keys.GetTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_keys.TagKey) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.short_name == 'short_name_value' + assert response.namespaced_name == 'namespaced_name_value' + assert response.description == 'description_value' + assert response.etag == 'etag_value' + + +def test_get_tag_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_key), + '__call__') as call: + client.get_tag_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.GetTagKeyRequest() + +@pytest.mark.asyncio +async def test_get_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.GetTagKeyRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.TagKey( + name='name_value', + parent='parent_value', + short_name='short_name_value', + namespaced_name='namespaced_name_value', + description='description_value', + etag='etag_value', + )) + response = await client.get_tag_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.GetTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_keys.TagKey) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.short_name == 'short_name_value' + assert response.namespaced_name == 'namespaced_name_value' + assert response.description == 'description_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_tag_key_async_from_dict(): + await test_get_tag_key_async(request_type=dict) + + +def test_get_tag_key_field_headers(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_keys.GetTagKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_key), + '__call__') as call: + call.return_value = tag_keys.TagKey() + client.get_tag_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_tag_key_field_headers_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_keys.GetTagKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.TagKey()) + await client.get_tag_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_tag_key_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_keys.TagKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tag_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_tag_key_flattened_error(): + client = TagKeysClient( + credentials=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_tag_key( + tag_keys.GetTagKeyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_tag_key_flattened_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_keys.TagKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.TagKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tag_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_tag_key_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tag_key( + tag_keys.GetTagKeyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.CreateTagKeyRequest, + dict, +]) +def test_create_tag_key(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_tag_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] == tag_keys.CreateTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_tag_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_key), + '__call__') as call: + client.create_tag_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.CreateTagKeyRequest() + +@pytest.mark.asyncio +async def test_create_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.CreateTagKeyRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_key), + '__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_tag_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.CreateTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_tag_key_async_from_dict(): + await test_create_tag_key_async(request_type=dict) + + +def test_create_tag_key_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_key), + '__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_tag_key( + tag_key=tag_keys.TagKey(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].tag_key + mock_val = tag_keys.TagKey(name='name_value') + assert arg == mock_val + + +def test_create_tag_key_flattened_error(): + client = TagKeysClient( + credentials=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_tag_key( + tag_keys.CreateTagKeyRequest(), + tag_key=tag_keys.TagKey(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_tag_key_flattened_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_key), + '__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_tag_key( + tag_key=tag_keys.TagKey(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].tag_key + mock_val = tag_keys.TagKey(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_tag_key_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tag_key( + tag_keys.CreateTagKeyRequest(), + tag_key=tag_keys.TagKey(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.UpdateTagKeyRequest, + dict, +]) +def test_update_tag_key(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_tag_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] == tag_keys.UpdateTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_tag_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_key), + '__call__') as call: + client.update_tag_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.UpdateTagKeyRequest() + +@pytest.mark.asyncio +async def test_update_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.UpdateTagKeyRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_tag_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.UpdateTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_tag_key_async_from_dict(): + await test_update_tag_key_async(request_type=dict) + + +def test_update_tag_key_field_headers(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_keys.UpdateTagKeyRequest() + + request.tag_key.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_key), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_tag_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', + 'tag_key.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tag_key_field_headers_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_keys.UpdateTagKeyRequest() + + request.tag_key.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_tag_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', + 'tag_key.name=name_value', + ) in kw['metadata'] + + +def test_update_tag_key_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag_key( + tag_key=tag_keys.TagKey(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].tag_key + mock_val = tag_keys.TagKey(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_tag_key_flattened_error(): + client = TagKeysClient( + credentials=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_tag_key( + tag_keys.UpdateTagKeyRequest(), + tag_key=tag_keys.TagKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_tag_key_flattened_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag_key( + tag_key=tag_keys.TagKey(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].tag_key + mock_val = tag_keys.TagKey(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_tag_key_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_tag_key( + tag_keys.UpdateTagKeyRequest(), + tag_key=tag_keys.TagKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.DeleteTagKeyRequest, + dict, +]) +def test_delete_tag_key(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_tag_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] == tag_keys.DeleteTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_tag_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + client.delete_tag_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.DeleteTagKeyRequest() + +@pytest.mark.asyncio +async def test_delete_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.DeleteTagKeyRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_tag_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_keys.DeleteTagKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_tag_key_async_from_dict(): + await test_delete_tag_key_async(request_type=dict) + + +def test_delete_tag_key_field_headers(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_keys.DeleteTagKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_tag_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_delete_tag_key_field_headers_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_keys.DeleteTagKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_tag_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_delete_tag_key_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_tag_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_delete_tag_key_flattened_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tag_key( + tag_keys.DeleteTagKeyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_tag_key_flattened_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_tag_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_delete_tag_key_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tag_key( + tag_keys.DeleteTagKeyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = TagKeysClient( + 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() + + +def test_get_iam_policy_flattened(): + client = TagKeysClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = TagKeysClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = TagKeysAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = TagKeysClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = TagKeysClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = TagKeysAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = TagKeysClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = TagKeysClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = TagKeysAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.ListTagKeysRequest, + dict, +]) +def test_list_tag_keys_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_keys.ListTagKeysResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_keys.ListTagKeysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_tag_keys(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagKeysPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tag_keys_rest_required_fields(request_type=tag_keys.ListTagKeysRequest): + transport_class = transports.TagKeysRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "parent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "parent" in jsonified_request + assert jsonified_request["parent"] == request_init["parent"] + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_keys._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "parent", )) + 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 = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tag_keys.ListTagKeysResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = tag_keys.ListTagKeysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_tag_keys(request) + + expected_params = [ + ( + "parent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_tag_keys_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_tag_keys._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_keys_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagKeysRestInterceptor, "post_list_tag_keys") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_list_tag_keys") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.ListTagKeysRequest.pb(tag_keys.ListTagKeysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tag_keys.ListTagKeysResponse.to_json(tag_keys.ListTagKeysResponse()) + + request = tag_keys.ListTagKeysRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_keys.ListTagKeysResponse() + + client.list_tag_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tag_keys_rest_bad_request(transport: str = 'rest', request_type=tag_keys.ListTagKeysRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tag_keys(request) + + +def test_list_tag_keys_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_keys.ListTagKeysResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_keys.ListTagKeysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_tag_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/v3/tagKeys" % client.transport._host, args[1]) + + +def test_list_tag_keys_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.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_tag_keys( + tag_keys.ListTagKeysRequest(), + parent='parent_value', + ) + + +def test_list_tag_keys_rest_pager(transport: str = 'rest'): + client = TagKeysClient( + 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 = ( + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + next_page_token='abc', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[], + next_page_token='def', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + ], + next_page_token='ghi', + ), + tag_keys.ListTagKeysResponse( + tag_keys=[ + tag_keys.TagKey(), + tag_keys.TagKey(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tag_keys.ListTagKeysResponse.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 = {} + + pager = client.list_tag_keys(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_keys.TagKey) + for i in results) + + pages = list(client.list_tag_keys(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + tag_keys.GetTagKeyRequest, + dict, +]) +def test_get_tag_key_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagKeys/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 = tag_keys.TagKey( + name='name_value', + parent='parent_value', + short_name='short_name_value', + namespaced_name='namespaced_name_value', + description='description_value', + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_keys.TagKey.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_tag_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_keys.TagKey) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.short_name == 'short_name_value' + assert response.namespaced_name == 'namespaced_name_value' + assert response.description == 'description_value' + assert response.etag == 'etag_value' + + +def test_get_tag_key_rest_required_fields(request_type=tag_keys.GetTagKeyRequest): + transport_class = transports.TagKeysRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_tag_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_tag_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 = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tag_keys.TagKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = tag_keys.TagKey.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_tag_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_tag_key_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_tag_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagKeysRestInterceptor, "post_get_tag_key") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_get_tag_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.GetTagKeyRequest.pb(tag_keys.GetTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tag_keys.TagKey.to_json(tag_keys.TagKey()) + + request = tag_keys.GetTagKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_keys.TagKey() + + client.get_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.GetTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagKeys/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_tag_key(request) + + +def test_get_tag_key_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_keys.TagKey() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'tagKeys/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_keys.TagKey.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_tag_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/v3/{name=tagKeys/*}" % client.transport._host, args[1]) + + +def test_get_tag_key_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.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_tag_key( + tag_keys.GetTagKeyRequest(), + name='name_value', + ) + + +def test_get_tag_key_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.CreateTagKeyRequest, + dict, +]) +def test_create_tag_key_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_key"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_tag_key(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_tag_key_rest_required_fields(request_type=tag_keys.CreateTagKeyRequest): + transport_class = transports.TagKeysRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tag_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()).create_tag_key._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = TagKeysClient( + 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_tag_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_tag_key_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_tag_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", )) & set(("tagKey", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_create_tag_key") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_create_tag_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.CreateTagKeyRequest.pb(tag_keys.CreateTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_keys.CreateTagKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.CreateTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_key"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_tag_key(request) + + +def test_create_tag_key_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {} + + # get truthy value for each flattened field + mock_args = dict( + tag_key=tag_keys.TagKey(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_tag_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/v3/tagKeys" % client.transport._host, args[1]) + + +def test_create_tag_key_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.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_tag_key( + tag_keys.CreateTagKeyRequest(), + tag_key=tag_keys.TagKey(name='name_value'), + ) + + +def test_create_tag_key_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.UpdateTagKeyRequest, + dict, +]) +def test_update_tag_key_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'tag_key': {'name': 'tagKeys/sample1'}} + request_init["tag_key"] = {'name': 'tagKeys/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_tag_key(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_tag_key_rest_required_fields(request_type=tag_keys.UpdateTagKeyRequest): + transport_class = transports.TagKeysRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_tag_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_tag_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", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_tag_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_tag_key_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_tag_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("tagKey", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_update_tag_key") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_update_tag_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.UpdateTagKeyRequest.pb(tag_keys.UpdateTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_keys.UpdateTagKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.UpdateTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'tag_key': {'name': 'tagKeys/sample1'}} + request_init["tag_key"] = {'name': 'tagKeys/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_tag_key(request) + + +def test_update_tag_key_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {'tag_key': {'name': 'tagKeys/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + tag_key=tag_keys.TagKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_tag_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/v3/{tag_key.name=tagKeys/*}" % client.transport._host, args[1]) + + +def test_update_tag_key_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.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_tag_key( + tag_keys.UpdateTagKeyRequest(), + tag_key=tag_keys.TagKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_tag_key_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_keys.DeleteTagKeyRequest, + dict, +]) +def test_delete_tag_key_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagKeys/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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_tag_key(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_tag_key_rest_required_fields(request_type=tag_keys.DeleteTagKeyRequest): + transport_class = transports.TagKeysRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_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()).delete_tag_key._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_tag_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_tag_key_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_tag_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_delete_tag_key") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_delete_tag_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.DeleteTagKeyRequest.pb(tag_keys.DeleteTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_keys.DeleteTagKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.DeleteTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagKeys/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_tag_key(request) + + +def test_delete_tag_key_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'tagKeys/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_tag_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/v3/{name=tagKeys/*}" % client.transport._host, args[1]) + + +def test_delete_tag_key_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tag_key( + tag_keys.DeleteTagKeyRequest(), + name='name_value', + ) + + +def test_delete_tag_key_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagKeys/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.TagKeysRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagKeysRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagKeys/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'tagKeys/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=tagKeys/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagKeys/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.TagKeysRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagKeysRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagKeys/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'tagKeys/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=tagKeys/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagKeys/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.TagKeysRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagKeysRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.TagKeysRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagKeys/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'tagKeys/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=tagKeys/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagKeysClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagKeysClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagKeysClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagKeysClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagKeysClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagKeysGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TagKeysGrpcTransport, + transports.TagKeysGrpcAsyncIOTransport, + transports.TagKeysRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = TagKeysClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TagKeysGrpcTransport, + ) + +def test_tag_keys_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TagKeysTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_tag_keys_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.resourcemanager_v3.services.tag_keys.transports.TagKeysTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TagKeysTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_tag_keys', + 'get_tag_key', + 'create_tag_key', + 'update_tag_key', + 'delete_tag_key', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + 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_tag_keys_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.resourcemanager_v3.services.tag_keys.transports.TagKeysTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TagKeysTransport( + 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/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +def test_tag_keys_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.resourcemanager_v3.services.tag_keys.transports.TagKeysTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TagKeysTransport() + adc.assert_called_once() + + +def test_tag_keys_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) + TagKeysClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagKeysGrpcTransport, + transports.TagKeysGrpcAsyncIOTransport, + ], +) +def test_tag_keys_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/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagKeysGrpcTransport, + transports.TagKeysGrpcAsyncIOTransport, + transports.TagKeysRestTransport, + ], +) +def test_tag_keys_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.TagKeysGrpcTransport, grpc_helpers), + (transports.TagKeysGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_tag_keys_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( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TagKeysGrpcTransport, transports.TagKeysGrpcAsyncIOTransport]) +def test_tag_keys_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_tag_keys_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.TagKeysRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_tag_keys_rest_lro_client(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_tag_keys_host_no_port(transport_name): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_tag_keys_host_with_port(transport_name): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_tag_keys_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TagKeysClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TagKeysClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_tag_keys._session + session2 = client2.transport.list_tag_keys._session + assert session1 != session2 + session1 = client1.transport.get_tag_key._session + session2 = client2.transport.get_tag_key._session + assert session1 != session2 + session1 = client1.transport.create_tag_key._session + session2 = client2.transport.create_tag_key._session + assert session1 != session2 + session1 = client1.transport.update_tag_key._session + session2 = client2.transport.update_tag_key._session + assert session1 != session2 + session1 = client1.transport.delete_tag_key._session + session2 = client2.transport.delete_tag_key._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 +def test_tag_keys_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TagKeysGrpcTransport( + 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_tag_keys_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TagKeysGrpcAsyncIOTransport( + 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.TagKeysGrpcTransport, transports.TagKeysGrpcAsyncIOTransport]) +def test_tag_keys_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.TagKeysGrpcTransport, transports.TagKeysGrpcAsyncIOTransport]) +def test_tag_keys_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_tag_keys_grpc_lro_client(): + client = TagKeysClient( + 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_tag_keys_grpc_lro_async_client(): + client = TagKeysAsyncClient( + 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_tag_key_path(): + tag_key = "squid" + expected = "tagKeys/{tag_key}".format(tag_key=tag_key, ) + actual = TagKeysClient.tag_key_path(tag_key) + assert expected == actual + + +def test_parse_tag_key_path(): + expected = { + "tag_key": "clam", + } + path = TagKeysClient.tag_key_path(**expected) + + # Check that the path construction is reversible. + actual = TagKeysClient.parse_tag_key_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TagKeysClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = TagKeysClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TagKeysClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = TagKeysClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = TagKeysClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TagKeysClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TagKeysClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = TagKeysClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TagKeysClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = TagKeysClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = TagKeysClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TagKeysClient.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 = TagKeysClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = TagKeysClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TagKeysClient.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.TagKeysTransport, '_prep_wrapped_messages') as prep: + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TagKeysTransport, '_prep_wrapped_messages') as prep: + transport_class = TagKeysClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = TagKeysAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = TagKeysClient( + 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", [ + (TagKeysClient, transports.TagKeysGrpcTransport), + (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py new file mode 100644 index 0000000..a090fc1 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py @@ -0,0 +1,5257 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.resourcemanager_v3.services.tag_values import TagValuesAsyncClient +from google.cloud.resourcemanager_v3.services.tag_values import TagValuesClient +from google.cloud.resourcemanager_v3.services.tag_values import pagers +from google.cloud.resourcemanager_v3.services.tag_values import transports +from google.cloud.resourcemanager_v3.types import tag_values +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 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert TagValuesClient._get_default_mtls_endpoint(None) is None + assert TagValuesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TagValuesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TagValuesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TagValuesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TagValuesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (TagValuesClient, "grpc"), + (TagValuesAsyncClient, "grpc_asyncio"), + (TagValuesClient, "rest"), +]) +def test_tag_values_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.TagValuesGrpcTransport, "grpc"), + (transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TagValuesRestTransport, "rest"), +]) +def test_tag_values_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", [ + (TagValuesClient, "grpc"), + (TagValuesAsyncClient, "grpc_asyncio"), + (TagValuesClient, "rest"), +]) +def test_tag_values_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 == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudresourcemanager.googleapis.com' + ) + + +def test_tag_values_client_get_transport_class(): + transport = TagValuesClient.get_transport_class() + available_transports = [ + transports.TagValuesGrpcTransport, + transports.TagValuesRestTransport, + ] + assert transport in available_transports + + transport = TagValuesClient.get_transport_class("grpc") + assert transport == transports.TagValuesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TagValuesClient, transports.TagValuesGrpcTransport, "grpc"), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio"), + (TagValuesClient, transports.TagValuesRestTransport, "rest"), +]) +@mock.patch.object(TagValuesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesClient)) +@mock.patch.object(TagValuesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesAsyncClient)) +def test_tag_values_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(TagValuesClient, '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(TagValuesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", "true"), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", "false"), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TagValuesClient, transports.TagValuesRestTransport, "rest", "true"), + (TagValuesClient, transports.TagValuesRestTransport, "rest", "false"), +]) +@mock.patch.object(TagValuesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesClient)) +@mock.patch.object(TagValuesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tag_values_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + TagValuesClient, TagValuesAsyncClient +]) +@mock.patch.object(TagValuesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesClient)) +@mock.patch.object(TagValuesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesAsyncClient)) +def test_tag_values_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TagValuesClient, transports.TagValuesGrpcTransport, "grpc"), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio"), + (TagValuesClient, transports.TagValuesRestTransport, "rest"), +]) +def test_tag_values_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", grpc_helpers), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TagValuesClient, transports.TagValuesRestTransport, "rest", None), +]) +def test_tag_values_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_tag_values_client_client_options_from_dict(): + with mock.patch('google.cloud.resourcemanager_v3.services.tag_values.transports.TagValuesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TagValuesClient( + 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", [ + (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", grpc_helpers), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_tag_values_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=None, + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.ListTagValuesRequest, + dict, +]) +def test_list_tag_values(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_values), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_values.ListTagValuesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_tag_values(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.ListTagValuesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagValuesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tag_values_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_values), + '__call__') as call: + client.list_tag_values() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.ListTagValuesRequest() + +@pytest.mark.asyncio +async def test_list_tag_values_async(transport: str = 'grpc_asyncio', request_type=tag_values.ListTagValuesRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_values), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_values.ListTagValuesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_tag_values(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.ListTagValuesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagValuesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_tag_values_async_from_dict(): + await test_list_tag_values_async(request_type=dict) + + +def test_list_tag_values_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_values), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_values.ListTagValuesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tag_values( + 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_tag_values_flattened_error(): + client = TagValuesClient( + credentials=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_tag_values( + tag_values.ListTagValuesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_tag_values_flattened_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_values), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_values.ListTagValuesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_values.ListTagValuesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tag_values( + 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_tag_values_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tag_values( + tag_values.ListTagValuesRequest(), + parent='parent_value', + ) + + +def test_list_tag_values_pager(transport_name: str = "grpc"): + client = TagValuesClient( + 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_tag_values), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + tag_values.TagValue(), + ], + next_page_token='abc', + ), + tag_values.ListTagValuesResponse( + tag_values=[], + next_page_token='def', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + ], + next_page_token='ghi', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_tag_values(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_values.TagValue) + for i in results) +def test_list_tag_values_pages(transport_name: str = "grpc"): + client = TagValuesClient( + 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_tag_values), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + tag_values.TagValue(), + ], + next_page_token='abc', + ), + tag_values.ListTagValuesResponse( + tag_values=[], + next_page_token='def', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + ], + next_page_token='ghi', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tag_values(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_tag_values_async_pager(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_values), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + tag_values.TagValue(), + ], + next_page_token='abc', + ), + tag_values.ListTagValuesResponse( + tag_values=[], + next_page_token='def', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + ], + next_page_token='ghi', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tag_values(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, tag_values.TagValue) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_tag_values_async_pages(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_values), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + tag_values.TagValue(), + ], + next_page_token='abc', + ), + tag_values.ListTagValuesResponse( + tag_values=[], + next_page_token='def', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + ], + next_page_token='ghi', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_tag_values(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + tag_values.GetTagValueRequest, + dict, +]) +def test_get_tag_value(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_values.TagValue( + name='name_value', + parent='parent_value', + short_name='short_name_value', + namespaced_name='namespaced_name_value', + description='description_value', + etag='etag_value', + ) + response = client.get_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.GetTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_values.TagValue) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.short_name == 'short_name_value' + assert response.namespaced_name == 'namespaced_name_value' + assert response.description == 'description_value' + assert response.etag == 'etag_value' + + +def test_get_tag_value_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_value), + '__call__') as call: + client.get_tag_value() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.GetTagValueRequest() + +@pytest.mark.asyncio +async def test_get_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.GetTagValueRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_values.TagValue( + name='name_value', + parent='parent_value', + short_name='short_name_value', + namespaced_name='namespaced_name_value', + description='description_value', + etag='etag_value', + )) + response = await client.get_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.GetTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_values.TagValue) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.short_name == 'short_name_value' + assert response.namespaced_name == 'namespaced_name_value' + assert response.description == 'description_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_tag_value_async_from_dict(): + await test_get_tag_value_async(request_type=dict) + + +def test_get_tag_value_field_headers(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_values.GetTagValueRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_value), + '__call__') as call: + call.return_value = tag_values.TagValue() + client.get_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_tag_value_field_headers_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_values.GetTagValueRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_value), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_values.TagValue()) + await client.get_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_tag_value_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_values.TagValue() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tag_value( + 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_tag_value_flattened_error(): + client = TagValuesClient( + credentials=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_tag_value( + tag_values.GetTagValueRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_tag_value_flattened_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = tag_values.TagValue() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_values.TagValue()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tag_value( + 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_tag_value_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tag_value( + tag_values.GetTagValueRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.CreateTagValueRequest, + dict, +]) +def test_create_tag_value(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.CreateTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_tag_value_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_value), + '__call__') as call: + client.create_tag_value() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.CreateTagValueRequest() + +@pytest.mark.asyncio +async def test_create_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.CreateTagValueRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_value), + '__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_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.CreateTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_tag_value_async_from_dict(): + await test_create_tag_value_async(request_type=dict) + + +def test_create_tag_value_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_value), + '__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_tag_value( + tag_value=tag_values.TagValue(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].tag_value + mock_val = tag_values.TagValue(name='name_value') + assert arg == mock_val + + +def test_create_tag_value_flattened_error(): + client = TagValuesClient( + credentials=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_tag_value( + tag_values.CreateTagValueRequest(), + tag_value=tag_values.TagValue(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_tag_value_flattened_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_value), + '__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_tag_value( + tag_value=tag_values.TagValue(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].tag_value + mock_val = tag_values.TagValue(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_tag_value_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tag_value( + tag_values.CreateTagValueRequest(), + tag_value=tag_values.TagValue(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.UpdateTagValueRequest, + dict, +]) +def test_update_tag_value(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.UpdateTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_tag_value_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_value), + '__call__') as call: + client.update_tag_value() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.UpdateTagValueRequest() + +@pytest.mark.asyncio +async def test_update_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.UpdateTagValueRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.UpdateTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_tag_value_async_from_dict(): + await test_update_tag_value_async(request_type=dict) + + +def test_update_tag_value_field_headers(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_values.UpdateTagValueRequest() + + request.tag_value.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_value), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tag_value.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_tag_value_field_headers_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_values.UpdateTagValueRequest() + + request.tag_value.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_value), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'tag_value.name=name_value', + ) in kw['metadata'] + + +def test_update_tag_value_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tag_value( + tag_value=tag_values.TagValue(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].tag_value + mock_val = tag_values.TagValue(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_tag_value_flattened_error(): + client = TagValuesClient( + credentials=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_tag_value( + tag_values.UpdateTagValueRequest(), + tag_value=tag_values.TagValue(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_tag_value_flattened_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tag_value( + tag_value=tag_values.TagValue(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].tag_value + mock_val = tag_values.TagValue(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_tag_value_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_tag_value( + tag_values.UpdateTagValueRequest(), + tag_value=tag_values.TagValue(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.DeleteTagValueRequest, + dict, +]) +def test_delete_tag_value(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.DeleteTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_tag_value_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + client.delete_tag_value() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.DeleteTagValueRequest() + +@pytest.mark.asyncio +async def test_delete_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.DeleteTagValueRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == tag_values.DeleteTagValueRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_tag_value_async_from_dict(): + await test_delete_tag_value_async(request_type=dict) + + +def test_delete_tag_value_field_headers(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_values.DeleteTagValueRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_tag_value_field_headers_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tag_values.DeleteTagValueRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_tag_value(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_tag_value_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_tag_value( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_tag_value_flattened_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tag_value( + tag_values.DeleteTagValueRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_tag_value_flattened_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_value), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_tag_value( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_tag_value_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tag_value( + tag_values.DeleteTagValueRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = TagValuesClient( + 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() + + +def test_get_iam_policy_flattened(): + client = TagValuesClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = TagValuesClient( + credentials=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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = TagValuesAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + 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) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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) + _, args, _ = call.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_foreign(): + client = TagValuesClient( + 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), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = TagValuesClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = TagValuesAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = TagValuesClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = TagValuesClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = TagValuesAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.ListTagValuesRequest, + dict, +]) +def test_list_tag_values_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_values.ListTagValuesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_values.ListTagValuesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_tag_values(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagValuesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_tag_values_rest_required_fields(request_type=tag_values.ListTagValuesRequest): + transport_class = transports.TagValuesRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "parent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_values._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "parent" in jsonified_request + assert jsonified_request["parent"] == request_init["parent"] + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_values._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "parent", )) + 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 = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tag_values.ListTagValuesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = tag_values.ListTagValuesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_tag_values(request) + + expected_params = [ + ( + "parent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_tag_values_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_tag_values._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_values_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagValuesRestInterceptor, "post_list_tag_values") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_list_tag_values") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.ListTagValuesRequest.pb(tag_values.ListTagValuesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tag_values.ListTagValuesResponse.to_json(tag_values.ListTagValuesResponse()) + + request = tag_values.ListTagValuesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_values.ListTagValuesResponse() + + client.list_tag_values(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tag_values_rest_bad_request(transport: str = 'rest', request_type=tag_values.ListTagValuesRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_tag_values(request) + + +def test_list_tag_values_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_values.ListTagValuesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_values.ListTagValuesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_tag_values(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/tagValues" % client.transport._host, args[1]) + + +def test_list_tag_values_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.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_tag_values( + tag_values.ListTagValuesRequest(), + parent='parent_value', + ) + + +def test_list_tag_values_rest_pager(transport: str = 'rest'): + client = TagValuesClient( + 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 = ( + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + tag_values.TagValue(), + ], + next_page_token='abc', + ), + tag_values.ListTagValuesResponse( + tag_values=[], + next_page_token='def', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + ], + next_page_token='ghi', + ), + tag_values.ListTagValuesResponse( + tag_values=[ + tag_values.TagValue(), + tag_values.TagValue(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tag_values.ListTagValuesResponse.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 = {} + + pager = client.list_tag_values(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_values.TagValue) + for i in results) + + pages = list(client.list_tag_values(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + tag_values.GetTagValueRequest, + dict, +]) +def test_get_tag_value_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagValues/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 = tag_values.TagValue( + name='name_value', + parent='parent_value', + short_name='short_name_value', + namespaced_name='namespaced_name_value', + description='description_value', + etag='etag_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_values.TagValue.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_tag_value(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_values.TagValue) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.short_name == 'short_name_value' + assert response.namespaced_name == 'namespaced_name_value' + assert response.description == 'description_value' + assert response.etag == 'etag_value' + + +def test_get_tag_value_rest_required_fields(request_type=tag_values.GetTagValueRequest): + transport_class = transports.TagValuesRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_tag_value._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_tag_value._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 = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tag_values.TagValue() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = tag_values.TagValue.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_tag_value(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_tag_value_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_tag_value._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagValuesRestInterceptor, "post_get_tag_value") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_get_tag_value") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.GetTagValueRequest.pb(tag_values.GetTagValueRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = tag_values.TagValue.to_json(tag_values.TagValue()) + + request = tag_values.GetTagValueRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_values.TagValue() + + client.get_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.GetTagValueRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagValues/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_tag_value(request) + + +def test_get_tag_value_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = tag_values.TagValue() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'tagValues/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = tag_values.TagValue.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_tag_value(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=tagValues/*}" % client.transport._host, args[1]) + + +def test_get_tag_value_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.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_tag_value( + tag_values.GetTagValueRequest(), + name='name_value', + ) + + +def test_get_tag_value_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.CreateTagValueRequest, + dict, +]) +def test_create_tag_value_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_value"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_tag_value(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_tag_value_rest_required_fields(request_type=tag_values.CreateTagValueRequest): + transport_class = transports.TagValuesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tag_value._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()).create_tag_value._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = TagValuesClient( + 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_tag_value(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_tag_value_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_tag_value._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", )) & set(("tagValue", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_create_tag_value") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_create_tag_value") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.CreateTagValueRequest.pb(tag_values.CreateTagValueRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_values.CreateTagValueRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.CreateTagValueRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_value"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_tag_value(request) + + +def test_create_tag_value_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {} + + # get truthy value for each flattened field + mock_args = dict( + tag_value=tag_values.TagValue(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_tag_value(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/tagValues" % client.transport._host, args[1]) + + +def test_create_tag_value_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.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_tag_value( + tag_values.CreateTagValueRequest(), + tag_value=tag_values.TagValue(name='name_value'), + ) + + +def test_create_tag_value_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.UpdateTagValueRequest, + dict, +]) +def test_update_tag_value_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'tag_value': {'name': 'tagValues/sample1'}} + request_init["tag_value"] = {'name': 'tagValues/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_tag_value(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_tag_value_rest_required_fields(request_type=tag_values.UpdateTagValueRequest): + transport_class = transports.TagValuesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_tag_value._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_tag_value._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_tag_value(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_tag_value_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_tag_value._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("tagValue", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_update_tag_value") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_update_tag_value") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.UpdateTagValueRequest.pb(tag_values.UpdateTagValueRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_values.UpdateTagValueRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.UpdateTagValueRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'tag_value': {'name': 'tagValues/sample1'}} + request_init["tag_value"] = {'name': 'tagValues/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_tag_value(request) + + +def test_update_tag_value_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = {'tag_value': {'name': 'tagValues/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + tag_value=tag_values.TagValue(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_tag_value(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{tag_value.name=tagValues/*}" % client.transport._host, args[1]) + + +def test_update_tag_value_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.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_tag_value( + tag_values.UpdateTagValueRequest(), + tag_value=tag_values.TagValue(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_tag_value_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + tag_values.DeleteTagValueRequest, + dict, +]) +def test_delete_tag_value_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagValues/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 = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_tag_value(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_tag_value_rest_required_fields(request_type=tag_values.DeleteTagValueRequest): + transport_class = transports.TagValuesRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_value._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_value._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_tag_value(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_tag_value_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_tag_value._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_delete_tag_value") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_delete_tag_value") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.DeleteTagValueRequest.pb(tag_values.DeleteTagValueRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = tag_values.DeleteTagValueRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.DeleteTagValueRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'tagValues/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_tag_value(request) + + +def test_delete_tag_value_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'tagValues/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_tag_value(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{name=tagValues/*}" % client.transport._host, args[1]) + + +def test_delete_tag_value_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tag_value( + tag_values.DeleteTagValueRequest(), + name='name_value', + ) + + +def test_delete_tag_value_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagValues/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.TagValuesRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagValuesRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagValues/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'tagValues/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=tagValues/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagValues/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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.TagValuesRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagValuesRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagValues/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'tagValues/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=tagValues/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagValues/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.TagValuesRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = 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 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.TagValuesRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.TagValuesRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'tagValues/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'tagValues/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v3/{resource=tagValues/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagValuesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagValuesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagValuesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagValuesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagValuesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagValuesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TagValuesGrpcTransport, + transports.TagValuesGrpcAsyncIOTransport, + transports.TagValuesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = TagValuesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TagValuesGrpcTransport, + ) + +def test_tag_values_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TagValuesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_tag_values_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.resourcemanager_v3.services.tag_values.transports.TagValuesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TagValuesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_tag_values', + 'get_tag_value', + 'create_tag_value', + 'update_tag_value', + 'delete_tag_value', + 'get_iam_policy', + 'set_iam_policy', + 'test_iam_permissions', + ) + 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_tag_values_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.resourcemanager_v3.services.tag_values.transports.TagValuesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TagValuesTransport( + 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/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +def test_tag_values_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.resourcemanager_v3.services.tag_values.transports.TagValuesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TagValuesTransport() + adc.assert_called_once() + + +def test_tag_values_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) + TagValuesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagValuesGrpcTransport, + transports.TagValuesGrpcAsyncIOTransport, + ], +) +def test_tag_values_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/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagValuesGrpcTransport, + transports.TagValuesGrpcAsyncIOTransport, + transports.TagValuesRestTransport, + ], +) +def test_tag_values_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.TagValuesGrpcTransport, grpc_helpers), + (transports.TagValuesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_tag_values_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( + "cloudresourcemanager.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/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="cloudresourcemanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TagValuesGrpcTransport, transports.TagValuesGrpcAsyncIOTransport]) +def test_tag_values_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_tag_values_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.TagValuesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_tag_values_rest_lro_client(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_tag_values_host_no_port(transport_name): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_tag_values_host_with_port(transport_name): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudresourcemanager.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudresourcemanager.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_tag_values_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TagValuesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TagValuesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_tag_values._session + session2 = client2.transport.list_tag_values._session + assert session1 != session2 + session1 = client1.transport.get_tag_value._session + session2 = client2.transport.get_tag_value._session + assert session1 != session2 + session1 = client1.transport.create_tag_value._session + session2 = client2.transport.create_tag_value._session + assert session1 != session2 + session1 = client1.transport.update_tag_value._session + session2 = client2.transport.update_tag_value._session + assert session1 != session2 + session1 = client1.transport.delete_tag_value._session + session2 = client2.transport.delete_tag_value._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 +def test_tag_values_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TagValuesGrpcTransport( + 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_tag_values_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TagValuesGrpcAsyncIOTransport( + 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.TagValuesGrpcTransport, transports.TagValuesGrpcAsyncIOTransport]) +def test_tag_values_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.TagValuesGrpcTransport, transports.TagValuesGrpcAsyncIOTransport]) +def test_tag_values_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_tag_values_grpc_lro_client(): + client = TagValuesClient( + 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_tag_values_grpc_lro_async_client(): + client = TagValuesAsyncClient( + 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_tag_value_path(): + tag_value = "squid" + expected = "tagValues/{tag_value}".format(tag_value=tag_value, ) + actual = TagValuesClient.tag_value_path(tag_value) + assert expected == actual + + +def test_parse_tag_value_path(): + expected = { + "tag_value": "clam", + } + path = TagValuesClient.tag_value_path(**expected) + + # Check that the path construction is reversible. + actual = TagValuesClient.parse_tag_value_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TagValuesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = TagValuesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TagValuesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = TagValuesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = TagValuesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TagValuesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TagValuesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = TagValuesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TagValuesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = TagValuesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = TagValuesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TagValuesClient.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 = TagValuesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = TagValuesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TagValuesClient.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.TagValuesTransport, '_prep_wrapped_messages') as prep: + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TagValuesTransport, '_prep_wrapped_messages') as prep: + transport_class = TagValuesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = TagValuesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = TagValuesClient( + 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", [ + (TagValuesClient, transports.TagValuesGrpcTransport), + (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 37c10cbe668b153744c5ccdf272ae05df4a40a60 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:04:29 +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 --- .../services/folders/async_client.py | 15 +- .../services/folders/client.py | 15 +- .../services/folders/transports/rest.py | 2 - .../services/organizations/async_client.py | 18 +- .../services/organizations/client.py | 18 +- .../services/organizations/transports/rest.py | 1 - .../services/projects/async_client.py | 16 +- .../services/projects/client.py | 16 +- .../services/projects/transports/rest.py | 8 - .../services/tag_bindings/transports/rest.py | 3 - .../services/tag_keys/async_client.py | 9 +- .../services/tag_keys/client.py | 9 +- .../services/tag_keys/transports/rest.py | 5 - .../services/tag_values/async_client.py | 9 +- .../services/tag_values/client.py | 9 +- .../services/tag_values/transports/rest.py | 5 - owl-bot-staging/v3/.coveragerc | 13 - owl-bot-staging/v3/.flake8 | 33 - owl-bot-staging/v3/MANIFEST.in | 2 - owl-bot-staging/v3/README.rst | 49 - owl-bot-staging/v3/docs/conf.py | 376 - owl-bot-staging/v3/docs/index.rst | 7 - .../v3/docs/resourcemanager_v3/folders.rst | 10 - .../docs/resourcemanager_v3/organizations.rst | 10 - .../v3/docs/resourcemanager_v3/projects.rst | 10 - .../v3/docs/resourcemanager_v3/services.rst | 11 - .../docs/resourcemanager_v3/tag_bindings.rst | 10 - .../v3/docs/resourcemanager_v3/tag_keys.rst | 10 - .../v3/docs/resourcemanager_v3/tag_values.rst | 10 - .../v3/docs/resourcemanager_v3/types.rst | 6 - .../google/cloud/resourcemanager/__init__.py | 177 - .../cloud/resourcemanager/gapic_version.py | 16 - .../v3/google/cloud/resourcemanager/py.typed | 2 - .../cloud/resourcemanager_v3/__init__.py | 178 - .../resourcemanager_v3/gapic_metadata.json | 813 -- .../cloud/resourcemanager_v3/gapic_version.py | 16 - .../google/cloud/resourcemanager_v3/py.typed | 2 - .../resourcemanager_v3/services/__init__.py | 15 - .../services/folders/__init__.py | 22 - .../services/folders/async_client.py | 1724 ---- .../services/folders/client.py | 1909 ----- .../services/folders/pagers.py | 260 - .../services/folders/transports/__init__.py | 38 - .../services/folders/transports/base.py | 316 - .../services/folders/transports/grpc.py | 662 -- .../folders/transports/grpc_asyncio.py | 661 -- .../services/folders/transports/rest.py | 1650 ---- .../services/organizations/__init__.py | 22 - .../services/organizations/async_client.py | 905 -- .../services/organizations/client.py | 1096 --- .../services/organizations/pagers.py | 139 - .../organizations/transports/__init__.py | 38 - .../services/organizations/transports/base.py | 219 - .../services/organizations/transports/grpc.py | 396 - .../organizations/transports/grpc_asyncio.py | 395 - .../services/organizations/transports/rest.py | 907 -- .../services/projects/__init__.py | 22 - .../services/projects/async_client.py | 1779 ---- .../services/projects/client.py | 1964 ----- .../services/projects/pagers.py | 260 - .../services/projects/transports/__init__.py | 38 - .../services/projects/transports/base.py | 316 - .../services/projects/transports/grpc.py | 684 -- .../projects/transports/grpc_asyncio.py | 683 -- .../services/projects/transports/rest.py | 1676 ---- .../services/tag_bindings/__init__.py | 22 - .../services/tag_bindings/async_client.py | 556 -- .../services/tag_bindings/client.py | 754 -- .../services/tag_bindings/pagers.py | 139 - .../tag_bindings/transports/__init__.py | 38 - .../services/tag_bindings/transports/base.py | 190 - .../services/tag_bindings/transports/grpc.py | 343 - .../tag_bindings/transports/grpc_asyncio.py | 342 - .../services/tag_bindings/transports/rest.py | 558 -- .../services/tag_keys/__init__.py | 22 - .../services/tag_keys/async_client.py | 1249 --- .../services/tag_keys/client.py | 1434 ---- .../services/tag_keys/pagers.py | 139 - .../services/tag_keys/transports/__init__.py | 38 - .../services/tag_keys/transports/base.py | 274 - .../services/tag_keys/transports/grpc.py | 487 -- .../tag_keys/transports/grpc_asyncio.py | 486 -- .../services/tag_keys/transports/rest.py | 1299 --- .../services/tag_values/__init__.py | 22 - .../services/tag_values/async_client.py | 1247 --- .../services/tag_values/client.py | 1432 ---- .../services/tag_values/pagers.py | 139 - .../tag_values/transports/__init__.py | 38 - .../services/tag_values/transports/base.py | 274 - .../services/tag_values/transports/grpc.py | 488 -- .../tag_values/transports/grpc_asyncio.py | 487 -- .../services/tag_values/transports/rest.py | 1301 --- .../resourcemanager_v3/types/__init__.py | 160 - .../cloud/resourcemanager_v3/types/folders.py | 495 -- .../resourcemanager_v3/types/organizations.py | 254 - .../resourcemanager_v3/types/projects.py | 584 -- .../resourcemanager_v3/types/tag_bindings.py | 194 - .../resourcemanager_v3/types/tag_keys.py | 302 - .../resourcemanager_v3/types/tag_values.py | 304 - owl-bot-staging/v3/mypy.ini | 3 - owl-bot-staging/v3/noxfile.py | 184 - ...3_generated_folders_create_folder_async.py | 59 - ...v3_generated_folders_create_folder_sync.py | 59 - ...3_generated_folders_delete_folder_async.py | 56 - ...v3_generated_folders_delete_folder_sync.py | 56 - ...r_v3_generated_folders_get_folder_async.py | 52 - ...er_v3_generated_folders_get_folder_sync.py | 52 - ..._generated_folders_get_iam_policy_async.py | 53 - ...3_generated_folders_get_iam_policy_sync.py | 53 - ...v3_generated_folders_list_folders_async.py | 53 - ..._v3_generated_folders_list_folders_sync.py | 53 - ..._v3_generated_folders_move_folder_async.py | 57 - ...r_v3_generated_folders_move_folder_sync.py | 57 - ..._generated_folders_search_folders_async.py | 52 - ...3_generated_folders_search_folders_sync.py | 52 - ..._generated_folders_set_iam_policy_async.py | 53 - ...3_generated_folders_set_iam_policy_sync.py | 53 - ...ated_folders_test_iam_permissions_async.py | 54 - ...rated_folders_test_iam_permissions_sync.py | 54 - ...generated_folders_undelete_folder_async.py | 56 - ..._generated_folders_undelete_folder_sync.py | 56 - ...3_generated_folders_update_folder_async.py | 59 - ...v3_generated_folders_update_folder_sync.py | 59 - ...ated_organizations_get_iam_policy_async.py | 53 - ...rated_organizations_get_iam_policy_sync.py | 53 - ...ed_organizations_get_organization_async.py | 52 - ...ted_organizations_get_organization_sync.py | 52 - ...rganizations_search_organizations_async.py | 52 - ...organizations_search_organizations_sync.py | 52 - ...ated_organizations_set_iam_policy_async.py | 53 - ...rated_organizations_set_iam_policy_sync.py | 53 - ...rganizations_test_iam_permissions_async.py | 54 - ...organizations_test_iam_permissions_sync.py | 54 - ...generated_projects_create_project_async.py | 55 - ..._generated_projects_create_project_sync.py | 55 - ...generated_projects_delete_project_async.py | 56 - ..._generated_projects_delete_project_sync.py | 56 - ...generated_projects_get_iam_policy_async.py | 53 - ..._generated_projects_get_iam_policy_sync.py | 53 - ...v3_generated_projects_get_project_async.py | 52 - ..._v3_generated_projects_get_project_sync.py | 52 - ..._generated_projects_list_projects_async.py | 53 - ...3_generated_projects_list_projects_sync.py | 53 - ...3_generated_projects_move_project_async.py | 57 - ...v3_generated_projects_move_project_sync.py | 57 - ...enerated_projects_search_projects_async.py | 52 - ...generated_projects_search_projects_sync.py | 52 - ...generated_projects_set_iam_policy_async.py | 53 - ..._generated_projects_set_iam_policy_sync.py | 53 - ...ted_projects_test_iam_permissions_async.py | 54 - ...ated_projects_test_iam_permissions_sync.py | 54 - ...nerated_projects_undelete_project_async.py | 56 - ...enerated_projects_undelete_project_sync.py | 56 - ...generated_projects_update_project_async.py | 55 - ..._generated_projects_update_project_sync.py | 55 - ...d_tag_bindings_create_tag_binding_async.py | 55 - ...ed_tag_bindings_create_tag_binding_sync.py | 55 - ...d_tag_bindings_delete_tag_binding_async.py | 56 - ...ed_tag_bindings_delete_tag_binding_sync.py | 56 - ...ed_tag_bindings_list_tag_bindings_async.py | 53 - ...ted_tag_bindings_list_tag_bindings_sync.py | 53 - ...generated_tag_keys_create_tag_key_async.py | 59 - ..._generated_tag_keys_create_tag_key_sync.py | 59 - ...generated_tag_keys_delete_tag_key_async.py | 56 - ..._generated_tag_keys_delete_tag_key_sync.py | 56 - ...generated_tag_keys_get_iam_policy_async.py | 53 - ..._generated_tag_keys_get_iam_policy_sync.py | 53 - ...v3_generated_tag_keys_get_tag_key_async.py | 52 - ..._v3_generated_tag_keys_get_tag_key_sync.py | 52 - ..._generated_tag_keys_list_tag_keys_async.py | 53 - ...3_generated_tag_keys_list_tag_keys_sync.py | 53 - ...generated_tag_keys_set_iam_policy_async.py | 53 - ..._generated_tag_keys_set_iam_policy_sync.py | 53 - ...ted_tag_keys_test_iam_permissions_async.py | 54 - ...ated_tag_keys_test_iam_permissions_sync.py | 54 - ...generated_tag_keys_update_tag_key_async.py | 59 - ..._generated_tag_keys_update_tag_key_sync.py | 59 - ...rated_tag_values_create_tag_value_async.py | 59 - ...erated_tag_values_create_tag_value_sync.py | 59 - ...rated_tag_values_delete_tag_value_async.py | 56 - ...erated_tag_values_delete_tag_value_sync.py | 56 - ...nerated_tag_values_get_iam_policy_async.py | 53 - ...enerated_tag_values_get_iam_policy_sync.py | 53 - ...enerated_tag_values_get_tag_value_async.py | 52 - ...generated_tag_values_get_tag_value_sync.py | 52 - ...erated_tag_values_list_tag_values_async.py | 53 - ...nerated_tag_values_list_tag_values_sync.py | 53 - ...nerated_tag_values_set_iam_policy_async.py | 53 - ...enerated_tag_values_set_iam_policy_sync.py | 53 - ...d_tag_values_test_iam_permissions_async.py | 54 - ...ed_tag_values_test_iam_permissions_sync.py | 54 - ...rated_tag_values_update_tag_value_async.py | 59 - ...erated_tag_values_update_tag_value_sync.py | 59 - ...adata_google.cloud.resourcemanager.v3.json | 7509 ----------------- .../fixup_resourcemanager_v3_keywords.py | 209 - owl-bot-staging/v3/setup.py | 91 - .../v3/testing/constraints-3.10.txt | 7 - .../v3/testing/constraints-3.11.txt | 7 - .../v3/testing/constraints-3.12.txt | 7 - .../v3/testing/constraints-3.7.txt | 10 - .../v3/testing/constraints-3.8.txt | 7 - .../v3/testing/constraints-3.9.txt | 7 - owl-bot-staging/v3/tests/__init__.py | 16 - owl-bot-staging/v3/tests/unit/__init__.py | 16 - .../v3/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/resourcemanager_v3/__init__.py | 16 - .../gapic/resourcemanager_v3/test_folders.py | 6753 --------------- .../resourcemanager_v3/test_organizations.py | 3765 --------- .../gapic/resourcemanager_v3/test_projects.py | 6759 --------------- .../resourcemanager_v3/test_tag_bindings.py | 2788 ------ .../gapic/resourcemanager_v3/test_tag_keys.py | 5257 ------------ .../resourcemanager_v3/test_tag_values.py | 5257 ------------ 212 files changed, 50 insertions(+), 80452 deletions(-) delete mode 100644 owl-bot-staging/v3/.coveragerc delete mode 100644 owl-bot-staging/v3/.flake8 delete mode 100644 owl-bot-staging/v3/MANIFEST.in delete mode 100644 owl-bot-staging/v3/README.rst delete mode 100644 owl-bot-staging/v3/docs/conf.py delete mode 100644 owl-bot-staging/v3/docs/index.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/services.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst delete mode 100644 owl-bot-staging/v3/docs/resourcemanager_v3/types.rst delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager/py.typed delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py delete mode 100644 owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py delete mode 100644 owl-bot-staging/v3/mypy.ini delete mode 100644 owl-bot-staging/v3/noxfile.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py delete mode 100644 owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json delete mode 100644 owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py delete mode 100644 owl-bot-staging/v3/setup.py delete mode 100644 owl-bot-staging/v3/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v3/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v3/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v3/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v3/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v3/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v3/tests/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py diff --git a/google/cloud/resourcemanager_v3/services/folders/async_client.py b/google/cloud/resourcemanager_v3/services/folders/async_client.py index a315099..20b75cd 100644 --- a/google/cloud/resourcemanager_v3/services/folders/async_client.py +++ b/google/cloud/resourcemanager_v3/services/folders/async_client.py @@ -816,10 +816,10 @@ async def sample_update_folder(): [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] method. - Only the `display_name` field can be changed. All other - fields will be ignored. Use the + Only the ``display_name`` field can be changed. All + other fields will be ignored. Use the [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] - method to change the `parent` field. + method to change the ``parent`` field. folder (:class:`google.cloud.resourcemanager_v3.types.Folder`): Required. The new definition of the Folder. It must include the ``name`` field, which cannot be changed. @@ -1345,8 +1345,7 @@ async def sample_get_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being requested. See the @@ -1524,8 +1523,7 @@ async def sample_set_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being specified. See the @@ -1696,8 +1694,7 @@ async def sample_test_iam_permissions(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (:class:`str`): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/folders/client.py b/google/cloud/resourcemanager_v3/services/folders/client.py index 75952b4..d86a8e9 100644 --- a/google/cloud/resourcemanager_v3/services/folders/client.py +++ b/google/cloud/resourcemanager_v3/services/folders/client.py @@ -1026,10 +1026,10 @@ def sample_update_folder(): [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] method. - Only the `display_name` field can be changed. All other - fields will be ignored. Use the + Only the ``display_name`` field can be changed. All + other fields will be ignored. Use the [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] - method to change the `parent` field. + method to change the ``parent`` field. folder (google.cloud.resourcemanager_v3.types.Folder): Required. The new definition of the Folder. It must include the ``name`` field, which cannot be changed. @@ -1555,8 +1555,7 @@ def sample_get_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being requested. See the @@ -1722,8 +1721,7 @@ def sample_set_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being specified. See the @@ -1891,8 +1889,7 @@ def sample_test_iam_permissions(): Args: request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (str): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/folders/transports/rest.py b/google/cloud/resourcemanager_v3/services/folders/transports/rest.py index 145db89..ad3d3b7 100644 --- a/google/cloud/resourcemanager_v3/services/folders/transports/rest.py +++ b/google/cloud/resourcemanager_v3/services/folders/transports/rest.py @@ -1179,7 +1179,6 @@ def __call__( request (~.folders.SearchFoldersRequest): The request object. The request message for searching folders. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1639,7 +1638,6 @@ def __call__( other fields will be ignored. Use the [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to change the ``parent`` field. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/resourcemanager_v3/services/organizations/async_client.py b/google/cloud/resourcemanager_v3/services/organizations/async_client.py index b61b16a..dd47ddb 100644 --- a/google/cloud/resourcemanager_v3/services/organizations/async_client.py +++ b/google/cloud/resourcemanager_v3/services/organizations/async_client.py @@ -258,9 +258,9 @@ async def sample_get_organization(): Args: request (Optional[Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]]): - The request object. The request sent to the - `GetOrganization` method. The `name` field is required. - `organization_id` is no longer accepted. + The request object. The request sent to the ``GetOrganization`` method. The + ``name`` field is required. ``organization_id`` is no + longer accepted. name (:class:`str`): Required. The resource name of the Organization to fetch. This is the organization's relative path in the @@ -381,8 +381,7 @@ async def sample_search_organizations(): Args: request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]]): - The request object. The request sent to the - `SearchOrganizations` method. + The request object. The request sent to the ``SearchOrganizations`` method. query (:class:`str`): Optional. An optional query string used to filter the Organizations to return in the response. Query rules are @@ -517,8 +516,7 @@ async def sample_get_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being requested. See the @@ -699,8 +697,7 @@ async def sample_set_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being specified. See the @@ -871,8 +868,7 @@ async def sample_test_iam_permissions(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (:class:`str`): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/organizations/client.py b/google/cloud/resourcemanager_v3/services/organizations/client.py index d1369cd..6f7231b 100644 --- a/google/cloud/resourcemanager_v3/services/organizations/client.py +++ b/google/cloud/resourcemanager_v3/services/organizations/client.py @@ -478,9 +478,9 @@ def sample_get_organization(): Args: request (Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]): - The request object. The request sent to the - `GetOrganization` method. The `name` field is required. - `organization_id` is no longer accepted. + The request object. The request sent to the ``GetOrganization`` method. The + ``name`` field is required. ``organization_id`` is no + longer accepted. name (str): Required. The resource name of the Organization to fetch. This is the organization's relative path in the @@ -592,8 +592,7 @@ def sample_search_organizations(): Args: request (Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]): - The request object. The request sent to the - `SearchOrganizations` method. + The request object. The request sent to the ``SearchOrganizations`` method. query (str): Optional. An optional query string used to filter the Organizations to return in the response. Query rules are @@ -728,8 +727,7 @@ def sample_get_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being requested. See the @@ -898,8 +896,7 @@ def sample_set_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being specified. See the @@ -1067,8 +1064,7 @@ def sample_test_iam_permissions(): Args: request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (str): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py b/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py index bbce119..367d390 100644 --- a/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py +++ b/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py @@ -519,7 +519,6 @@ def __call__( The request object. The request sent to the ``GetOrganization`` method. The ``name`` field is required. ``organization_id`` is no longer accepted. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/resourcemanager_v3/services/projects/async_client.py b/google/cloud/resourcemanager_v3/services/projects/async_client.py index fb2b070..6290f18 100644 --- a/google/cloud/resourcemanager_v3/services/projects/async_client.py +++ b/google/cloud/resourcemanager_v3/services/projects/async_client.py @@ -809,10 +809,10 @@ async def sample_update_project(): [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] method. - Only the `display_name` and `labels` fields can be + Only the ``display_name`` and ``labels`` fields can be change. Use the [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method to change the `parent` field. + method to change the ``parent`` field. project (:class:`google.cloud.resourcemanager_v3.types.Project`): Required. The new definition of the project. @@ -1237,8 +1237,7 @@ async def sample_undelete_project(): Args: request (Optional[Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]]): - The request object. The request sent to the - [UndeleteProject] + The request object. The request sent to the [UndeleteProject] [google.cloud.resourcemanager.v3.Projects.UndeleteProject] method. name (:class:`str`): @@ -1357,8 +1356,7 @@ async def sample_get_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being requested. See the @@ -1583,8 +1581,7 @@ async def sample_set_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being specified. See the @@ -1752,8 +1749,7 @@ async def sample_test_iam_permissions(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (:class:`str`): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/projects/client.py b/google/cloud/resourcemanager_v3/services/projects/client.py index 8c578d0..8d60db5 100644 --- a/google/cloud/resourcemanager_v3/services/projects/client.py +++ b/google/cloud/resourcemanager_v3/services/projects/client.py @@ -1019,10 +1019,10 @@ def sample_update_project(): [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] method. - Only the `display_name` and `labels` fields can be + Only the ``display_name`` and ``labels`` fields can be change. Use the [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method to change the `parent` field. + method to change the ``parent`` field. project (google.cloud.resourcemanager_v3.types.Project): Required. The new definition of the project. @@ -1447,8 +1447,7 @@ def sample_undelete_project(): Args: request (Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]): - The request object. The request sent to the - [UndeleteProject] + The request object. The request sent to the [UndeleteProject] [google.cloud.resourcemanager.v3.Projects.UndeleteProject] method. name (str): @@ -1567,8 +1566,7 @@ def sample_get_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being requested. See the @@ -1781,8 +1779,7 @@ def sample_set_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being specified. See the @@ -1947,8 +1944,7 @@ def sample_test_iam_permissions(): Args: request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (str): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/projects/transports/rest.py b/google/cloud/resourcemanager_v3/services/projects/transports/rest.py index 94491f1..44e4d4c 100644 --- a/google/cloud/resourcemanager_v3/services/projects/transports/rest.py +++ b/google/cloud/resourcemanager_v3/services/projects/transports/rest.py @@ -569,7 +569,6 @@ def __call__( The request object. The request sent to the [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -667,7 +666,6 @@ def __call__( request (~.projects.DeleteProjectRequest): The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -927,7 +925,6 @@ def __call__( The request object. The request sent to the [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1022,7 +1019,6 @@ def __call__( The request object. The request sent to the [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1122,7 +1118,6 @@ def __call__( The request object. The request sent to [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1211,7 +1206,6 @@ def __call__( The request object. The request sent to the [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1573,7 +1567,6 @@ def __call__( The request object. The request sent to the [UndeleteProject] [google.cloud.resourcemanager.v3.Projects.UndeleteProject] method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1679,7 +1672,6 @@ def __call__( change. Use the [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] method to change the ``parent`` field. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py b/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py index 30d00db..2808039 100644 --- a/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py +++ b/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py @@ -332,7 +332,6 @@ def __call__( request (~.tag_bindings.CreateTagBindingRequest): The request object. The request message to create a TagBinding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -432,7 +431,6 @@ def __call__( request (~.tag_bindings.DeleteTagBindingRequest): The request object. The request message to delete a TagBinding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -525,7 +523,6 @@ def __call__( request (~.tag_bindings.ListTagBindingsRequest): The request object. The request message to list all TagBindings for a parent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py b/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py index 0d9f3c8..cce9b16 100644 --- a/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py +++ b/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py @@ -865,8 +865,7 @@ async def sample_get_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being requested. See the @@ -1044,8 +1043,7 @@ async def sample_set_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being specified. See the @@ -1216,8 +1214,7 @@ async def sample_test_iam_permissions(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (:class:`str`): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/tag_keys/client.py b/google/cloud/resourcemanager_v3/services/tag_keys/client.py index 5548403..34cf9df 100644 --- a/google/cloud/resourcemanager_v3/services/tag_keys/client.py +++ b/google/cloud/resourcemanager_v3/services/tag_keys/client.py @@ -1075,8 +1075,7 @@ def sample_get_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being requested. See the @@ -1242,8 +1241,7 @@ def sample_set_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being specified. See the @@ -1411,8 +1409,7 @@ def sample_test_iam_permissions(): Args: request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (str): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py b/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py index 1c19d71..f8978cd 100644 --- a/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py +++ b/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py @@ -471,7 +471,6 @@ def __call__( request (~.tag_keys.CreateTagKeyRequest): The request object. The request message for creating a TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -569,7 +568,6 @@ def __call__( request (~.tag_keys.DeleteTagKeyRequest): The request object. The request message for deleting a TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -828,7 +826,6 @@ def __call__( request (~.tag_keys.GetTagKeyRequest): The request object. The request message for getting a TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -920,7 +917,6 @@ def __call__( request (~.tag_keys.ListTagKeysRequest): The request object. The request message for listing all TagKeys under a parent resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1275,7 +1271,6 @@ def __call__( request (~.tag_keys.UpdateTagKeyRequest): The request object. The request message for updating a TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/google/cloud/resourcemanager_v3/services/tag_values/async_client.py b/google/cloud/resourcemanager_v3/services/tag_values/async_client.py index f0b9185..833f345 100644 --- a/google/cloud/resourcemanager_v3/services/tag_values/async_client.py +++ b/google/cloud/resourcemanager_v3/services/tag_values/async_client.py @@ -865,8 +865,7 @@ async def sample_get_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being requested. See the @@ -1044,8 +1043,7 @@ async def sample_set_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being specified. See the @@ -1216,8 +1214,7 @@ async def sample_test_iam_permissions(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (:class:`str`): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/tag_values/client.py b/google/cloud/resourcemanager_v3/services/tag_values/client.py index 3247eda..c36de38 100644 --- a/google/cloud/resourcemanager_v3/services/tag_values/client.py +++ b/google/cloud/resourcemanager_v3/services/tag_values/client.py @@ -1073,8 +1073,7 @@ def sample_get_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being requested. See the @@ -1240,8 +1239,7 @@ def sample_set_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being specified. See the @@ -1409,8 +1407,7 @@ def sample_test_iam_permissions(): Args: request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (str): REQUIRED: The resource for which the policy detail is being requested. See diff --git a/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py b/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py index 3bd88e6..8dfe395 100644 --- a/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py +++ b/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py @@ -481,7 +481,6 @@ def __call__( request (~.tag_values.CreateTagValueRequest): The request object. The request message for creating a TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -581,7 +580,6 @@ def __call__( request (~.tag_values.DeleteTagValueRequest): The request object. The request message for deleting a TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -842,7 +840,6 @@ def __call__( request (~.tag_values.GetTagValueRequest): The request object. The request message for getting a TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -936,7 +933,6 @@ def __call__( request (~.tag_values.ListTagValuesRequest): The request object. The request message for listing TagValues for the specified TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1291,7 +1287,6 @@ def __call__( request (~.tag_values.UpdateTagValueRequest): The request object. The request message for updating a TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/owl-bot-staging/v3/.coveragerc b/owl-bot-staging/v3/.coveragerc deleted file mode 100644 index 174fd94..0000000 --- a/owl-bot-staging/v3/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/resourcemanager/__init__.py - google/cloud/resourcemanager/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/v3/.flake8 b/owl-bot-staging/v3/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v3/.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/v3/MANIFEST.in b/owl-bot-staging/v3/MANIFEST.in deleted file mode 100644 index 98a88f5..0000000 --- a/owl-bot-staging/v3/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/resourcemanager *.py -recursive-include google/cloud/resourcemanager_v3 *.py diff --git a/owl-bot-staging/v3/README.rst b/owl-bot-staging/v3/README.rst deleted file mode 100644 index eb02798..0000000 --- a/owl-bot-staging/v3/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Resourcemanager 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 Resourcemanager 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/v3/docs/conf.py b/owl-bot-staging/v3/docs/conf.py deleted file mode 100644 index e45af88..0000000 --- a/owl-bot-staging/v3/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-resource-manager 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-resource-manager" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud 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-resource-manager-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-resource-manager.tex", - u"google-cloud-resource-manager 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-resource-manager", - u"Google Cloud Resourcemanager 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-resource-manager", - u"google-cloud-resource-manager Documentation", - author, - "google-cloud-resource-manager", - "GAPIC library for Google Cloud Resourcemanager 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/v3/docs/index.rst b/owl-bot-staging/v3/docs/index.rst deleted file mode 100644 index 095c171..0000000 --- a/owl-bot-staging/v3/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - resourcemanager_v3/services - resourcemanager_v3/types diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst deleted file mode 100644 index 3e84ddf..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/folders.rst +++ /dev/null @@ -1,10 +0,0 @@ -Folders -------------------------- - -.. automodule:: google.cloud.resourcemanager_v3.services.folders - :members: - :inherited-members: - -.. automodule:: google.cloud.resourcemanager_v3.services.folders.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst deleted file mode 100644 index 30d36b0..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/organizations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Organizations -------------------------------- - -.. automodule:: google.cloud.resourcemanager_v3.services.organizations - :members: - :inherited-members: - -.. automodule:: google.cloud.resourcemanager_v3.services.organizations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst deleted file mode 100644 index 496baf0..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/projects.rst +++ /dev/null @@ -1,10 +0,0 @@ -Projects --------------------------- - -.. automodule:: google.cloud.resourcemanager_v3.services.projects - :members: - :inherited-members: - -.. automodule:: google.cloud.resourcemanager_v3.services.projects.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/services.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/services.rst deleted file mode 100644 index c542a30..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/services.rst +++ /dev/null @@ -1,11 +0,0 @@ -Services for Google Cloud Resourcemanager v3 API -================================================ -.. toctree:: - :maxdepth: 2 - - folders - organizations - projects - tag_bindings - tag_keys - tag_values diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst deleted file mode 100644 index 313ea3d..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_bindings.rst +++ /dev/null @@ -1,10 +0,0 @@ -TagBindings ------------------------------ - -.. automodule:: google.cloud.resourcemanager_v3.services.tag_bindings - :members: - :inherited-members: - -.. automodule:: google.cloud.resourcemanager_v3.services.tag_bindings.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst deleted file mode 100644 index f8d408f..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_keys.rst +++ /dev/null @@ -1,10 +0,0 @@ -TagKeys -------------------------- - -.. automodule:: google.cloud.resourcemanager_v3.services.tag_keys - :members: - :inherited-members: - -.. automodule:: google.cloud.resourcemanager_v3.services.tag_keys.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst deleted file mode 100644 index f4fa247..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/tag_values.rst +++ /dev/null @@ -1,10 +0,0 @@ -TagValues ---------------------------- - -.. automodule:: google.cloud.resourcemanager_v3.services.tag_values - :members: - :inherited-members: - -.. automodule:: google.cloud.resourcemanager_v3.services.tag_values.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/resourcemanager_v3/types.rst b/owl-bot-staging/v3/docs/resourcemanager_v3/types.rst deleted file mode 100644 index c265f6e..0000000 --- a/owl-bot-staging/v3/docs/resourcemanager_v3/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Resourcemanager v3 API -============================================= - -.. automodule:: google.cloud.resourcemanager_v3.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py deleted file mode 100644 index 0a90129..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager/__init__.py +++ /dev/null @@ -1,177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.resourcemanager import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.resourcemanager_v3.services.folders.client import FoldersClient -from google.cloud.resourcemanager_v3.services.folders.async_client import FoldersAsyncClient -from google.cloud.resourcemanager_v3.services.organizations.client import OrganizationsClient -from google.cloud.resourcemanager_v3.services.organizations.async_client import OrganizationsAsyncClient -from google.cloud.resourcemanager_v3.services.projects.client import ProjectsClient -from google.cloud.resourcemanager_v3.services.projects.async_client import ProjectsAsyncClient -from google.cloud.resourcemanager_v3.services.tag_bindings.client import TagBindingsClient -from google.cloud.resourcemanager_v3.services.tag_bindings.async_client import TagBindingsAsyncClient -from google.cloud.resourcemanager_v3.services.tag_keys.client import TagKeysClient -from google.cloud.resourcemanager_v3.services.tag_keys.async_client import TagKeysAsyncClient -from google.cloud.resourcemanager_v3.services.tag_values.client import TagValuesClient -from google.cloud.resourcemanager_v3.services.tag_values.async_client import TagValuesAsyncClient - -from google.cloud.resourcemanager_v3.types.folders import CreateFolderMetadata -from google.cloud.resourcemanager_v3.types.folders import CreateFolderRequest -from google.cloud.resourcemanager_v3.types.folders import DeleteFolderMetadata -from google.cloud.resourcemanager_v3.types.folders import DeleteFolderRequest -from google.cloud.resourcemanager_v3.types.folders import Folder -from google.cloud.resourcemanager_v3.types.folders import GetFolderRequest -from google.cloud.resourcemanager_v3.types.folders import ListFoldersRequest -from google.cloud.resourcemanager_v3.types.folders import ListFoldersResponse -from google.cloud.resourcemanager_v3.types.folders import MoveFolderMetadata -from google.cloud.resourcemanager_v3.types.folders import MoveFolderRequest -from google.cloud.resourcemanager_v3.types.folders import SearchFoldersRequest -from google.cloud.resourcemanager_v3.types.folders import SearchFoldersResponse -from google.cloud.resourcemanager_v3.types.folders import UndeleteFolderMetadata -from google.cloud.resourcemanager_v3.types.folders import UndeleteFolderRequest -from google.cloud.resourcemanager_v3.types.folders import UpdateFolderMetadata -from google.cloud.resourcemanager_v3.types.folders import UpdateFolderRequest -from google.cloud.resourcemanager_v3.types.organizations import DeleteOrganizationMetadata -from google.cloud.resourcemanager_v3.types.organizations import GetOrganizationRequest -from google.cloud.resourcemanager_v3.types.organizations import Organization -from google.cloud.resourcemanager_v3.types.organizations import SearchOrganizationsRequest -from google.cloud.resourcemanager_v3.types.organizations import SearchOrganizationsResponse -from google.cloud.resourcemanager_v3.types.organizations import UndeleteOrganizationMetadata -from google.cloud.resourcemanager_v3.types.projects import CreateProjectMetadata -from google.cloud.resourcemanager_v3.types.projects import CreateProjectRequest -from google.cloud.resourcemanager_v3.types.projects import DeleteProjectMetadata -from google.cloud.resourcemanager_v3.types.projects import DeleteProjectRequest -from google.cloud.resourcemanager_v3.types.projects import GetProjectRequest -from google.cloud.resourcemanager_v3.types.projects import ListProjectsRequest -from google.cloud.resourcemanager_v3.types.projects import ListProjectsResponse -from google.cloud.resourcemanager_v3.types.projects import MoveProjectMetadata -from google.cloud.resourcemanager_v3.types.projects import MoveProjectRequest -from google.cloud.resourcemanager_v3.types.projects import Project -from google.cloud.resourcemanager_v3.types.projects import SearchProjectsRequest -from google.cloud.resourcemanager_v3.types.projects import SearchProjectsResponse -from google.cloud.resourcemanager_v3.types.projects import UndeleteProjectMetadata -from google.cloud.resourcemanager_v3.types.projects import UndeleteProjectRequest -from google.cloud.resourcemanager_v3.types.projects import UpdateProjectMetadata -from google.cloud.resourcemanager_v3.types.projects import UpdateProjectRequest -from google.cloud.resourcemanager_v3.types.tag_bindings import CreateTagBindingMetadata -from google.cloud.resourcemanager_v3.types.tag_bindings import CreateTagBindingRequest -from google.cloud.resourcemanager_v3.types.tag_bindings import DeleteTagBindingMetadata -from google.cloud.resourcemanager_v3.types.tag_bindings import DeleteTagBindingRequest -from google.cloud.resourcemanager_v3.types.tag_bindings import ListTagBindingsRequest -from google.cloud.resourcemanager_v3.types.tag_bindings import ListTagBindingsResponse -from google.cloud.resourcemanager_v3.types.tag_bindings import TagBinding -from google.cloud.resourcemanager_v3.types.tag_keys import CreateTagKeyMetadata -from google.cloud.resourcemanager_v3.types.tag_keys import CreateTagKeyRequest -from google.cloud.resourcemanager_v3.types.tag_keys import DeleteTagKeyMetadata -from google.cloud.resourcemanager_v3.types.tag_keys import DeleteTagKeyRequest -from google.cloud.resourcemanager_v3.types.tag_keys import GetTagKeyRequest -from google.cloud.resourcemanager_v3.types.tag_keys import ListTagKeysRequest -from google.cloud.resourcemanager_v3.types.tag_keys import ListTagKeysResponse -from google.cloud.resourcemanager_v3.types.tag_keys import TagKey -from google.cloud.resourcemanager_v3.types.tag_keys import UpdateTagKeyMetadata -from google.cloud.resourcemanager_v3.types.tag_keys import UpdateTagKeyRequest -from google.cloud.resourcemanager_v3.types.tag_values import CreateTagValueMetadata -from google.cloud.resourcemanager_v3.types.tag_values import CreateTagValueRequest -from google.cloud.resourcemanager_v3.types.tag_values import DeleteTagValueMetadata -from google.cloud.resourcemanager_v3.types.tag_values import DeleteTagValueRequest -from google.cloud.resourcemanager_v3.types.tag_values import GetTagValueRequest -from google.cloud.resourcemanager_v3.types.tag_values import ListTagValuesRequest -from google.cloud.resourcemanager_v3.types.tag_values import ListTagValuesResponse -from google.cloud.resourcemanager_v3.types.tag_values import TagValue -from google.cloud.resourcemanager_v3.types.tag_values import UpdateTagValueMetadata -from google.cloud.resourcemanager_v3.types.tag_values import UpdateTagValueRequest - -__all__ = ('FoldersClient', - 'FoldersAsyncClient', - 'OrganizationsClient', - 'OrganizationsAsyncClient', - 'ProjectsClient', - 'ProjectsAsyncClient', - 'TagBindingsClient', - 'TagBindingsAsyncClient', - 'TagKeysClient', - 'TagKeysAsyncClient', - 'TagValuesClient', - 'TagValuesAsyncClient', - 'CreateFolderMetadata', - 'CreateFolderRequest', - 'DeleteFolderMetadata', - 'DeleteFolderRequest', - 'Folder', - 'GetFolderRequest', - 'ListFoldersRequest', - 'ListFoldersResponse', - 'MoveFolderMetadata', - 'MoveFolderRequest', - 'SearchFoldersRequest', - 'SearchFoldersResponse', - 'UndeleteFolderMetadata', - 'UndeleteFolderRequest', - 'UpdateFolderMetadata', - 'UpdateFolderRequest', - 'DeleteOrganizationMetadata', - 'GetOrganizationRequest', - 'Organization', - 'SearchOrganizationsRequest', - 'SearchOrganizationsResponse', - 'UndeleteOrganizationMetadata', - 'CreateProjectMetadata', - 'CreateProjectRequest', - 'DeleteProjectMetadata', - 'DeleteProjectRequest', - 'GetProjectRequest', - 'ListProjectsRequest', - 'ListProjectsResponse', - 'MoveProjectMetadata', - 'MoveProjectRequest', - 'Project', - 'SearchProjectsRequest', - 'SearchProjectsResponse', - 'UndeleteProjectMetadata', - 'UndeleteProjectRequest', - 'UpdateProjectMetadata', - 'UpdateProjectRequest', - 'CreateTagBindingMetadata', - 'CreateTagBindingRequest', - 'DeleteTagBindingMetadata', - 'DeleteTagBindingRequest', - 'ListTagBindingsRequest', - 'ListTagBindingsResponse', - 'TagBinding', - 'CreateTagKeyMetadata', - 'CreateTagKeyRequest', - 'DeleteTagKeyMetadata', - 'DeleteTagKeyRequest', - 'GetTagKeyRequest', - 'ListTagKeysRequest', - 'ListTagKeysResponse', - 'TagKey', - 'UpdateTagKeyMetadata', - 'UpdateTagKeyRequest', - 'CreateTagValueMetadata', - 'CreateTagValueRequest', - 'DeleteTagValueMetadata', - 'DeleteTagValueRequest', - 'GetTagValueRequest', - 'ListTagValuesRequest', - 'ListTagValuesResponse', - 'TagValue', - 'UpdateTagValueMetadata', - 'UpdateTagValueRequest', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py b/owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager/py.typed b/owl-bot-staging/v3/google/cloud/resourcemanager/py.typed deleted file mode 100644 index b1e13d7..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-resource-manager package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py deleted file mode 100644 index 16ccc26..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/__init__.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.folders import FoldersClient -from .services.folders import FoldersAsyncClient -from .services.organizations import OrganizationsClient -from .services.organizations import OrganizationsAsyncClient -from .services.projects import ProjectsClient -from .services.projects import ProjectsAsyncClient -from .services.tag_bindings import TagBindingsClient -from .services.tag_bindings import TagBindingsAsyncClient -from .services.tag_keys import TagKeysClient -from .services.tag_keys import TagKeysAsyncClient -from .services.tag_values import TagValuesClient -from .services.tag_values import TagValuesAsyncClient - -from .types.folders import CreateFolderMetadata -from .types.folders import CreateFolderRequest -from .types.folders import DeleteFolderMetadata -from .types.folders import DeleteFolderRequest -from .types.folders import Folder -from .types.folders import GetFolderRequest -from .types.folders import ListFoldersRequest -from .types.folders import ListFoldersResponse -from .types.folders import MoveFolderMetadata -from .types.folders import MoveFolderRequest -from .types.folders import SearchFoldersRequest -from .types.folders import SearchFoldersResponse -from .types.folders import UndeleteFolderMetadata -from .types.folders import UndeleteFolderRequest -from .types.folders import UpdateFolderMetadata -from .types.folders import UpdateFolderRequest -from .types.organizations import DeleteOrganizationMetadata -from .types.organizations import GetOrganizationRequest -from .types.organizations import Organization -from .types.organizations import SearchOrganizationsRequest -from .types.organizations import SearchOrganizationsResponse -from .types.organizations import UndeleteOrganizationMetadata -from .types.projects import CreateProjectMetadata -from .types.projects import CreateProjectRequest -from .types.projects import DeleteProjectMetadata -from .types.projects import DeleteProjectRequest -from .types.projects import GetProjectRequest -from .types.projects import ListProjectsRequest -from .types.projects import ListProjectsResponse -from .types.projects import MoveProjectMetadata -from .types.projects import MoveProjectRequest -from .types.projects import Project -from .types.projects import SearchProjectsRequest -from .types.projects import SearchProjectsResponse -from .types.projects import UndeleteProjectMetadata -from .types.projects import UndeleteProjectRequest -from .types.projects import UpdateProjectMetadata -from .types.projects import UpdateProjectRequest -from .types.tag_bindings import CreateTagBindingMetadata -from .types.tag_bindings import CreateTagBindingRequest -from .types.tag_bindings import DeleteTagBindingMetadata -from .types.tag_bindings import DeleteTagBindingRequest -from .types.tag_bindings import ListTagBindingsRequest -from .types.tag_bindings import ListTagBindingsResponse -from .types.tag_bindings import TagBinding -from .types.tag_keys import CreateTagKeyMetadata -from .types.tag_keys import CreateTagKeyRequest -from .types.tag_keys import DeleteTagKeyMetadata -from .types.tag_keys import DeleteTagKeyRequest -from .types.tag_keys import GetTagKeyRequest -from .types.tag_keys import ListTagKeysRequest -from .types.tag_keys import ListTagKeysResponse -from .types.tag_keys import TagKey -from .types.tag_keys import UpdateTagKeyMetadata -from .types.tag_keys import UpdateTagKeyRequest -from .types.tag_values import CreateTagValueMetadata -from .types.tag_values import CreateTagValueRequest -from .types.tag_values import DeleteTagValueMetadata -from .types.tag_values import DeleteTagValueRequest -from .types.tag_values import GetTagValueRequest -from .types.tag_values import ListTagValuesRequest -from .types.tag_values import ListTagValuesResponse -from .types.tag_values import TagValue -from .types.tag_values import UpdateTagValueMetadata -from .types.tag_values import UpdateTagValueRequest - -__all__ = ( - 'FoldersAsyncClient', - 'OrganizationsAsyncClient', - 'ProjectsAsyncClient', - 'TagBindingsAsyncClient', - 'TagKeysAsyncClient', - 'TagValuesAsyncClient', -'CreateFolderMetadata', -'CreateFolderRequest', -'CreateProjectMetadata', -'CreateProjectRequest', -'CreateTagBindingMetadata', -'CreateTagBindingRequest', -'CreateTagKeyMetadata', -'CreateTagKeyRequest', -'CreateTagValueMetadata', -'CreateTagValueRequest', -'DeleteFolderMetadata', -'DeleteFolderRequest', -'DeleteOrganizationMetadata', -'DeleteProjectMetadata', -'DeleteProjectRequest', -'DeleteTagBindingMetadata', -'DeleteTagBindingRequest', -'DeleteTagKeyMetadata', -'DeleteTagKeyRequest', -'DeleteTagValueMetadata', -'DeleteTagValueRequest', -'Folder', -'FoldersClient', -'GetFolderRequest', -'GetOrganizationRequest', -'GetProjectRequest', -'GetTagKeyRequest', -'GetTagValueRequest', -'ListFoldersRequest', -'ListFoldersResponse', -'ListProjectsRequest', -'ListProjectsResponse', -'ListTagBindingsRequest', -'ListTagBindingsResponse', -'ListTagKeysRequest', -'ListTagKeysResponse', -'ListTagValuesRequest', -'ListTagValuesResponse', -'MoveFolderMetadata', -'MoveFolderRequest', -'MoveProjectMetadata', -'MoveProjectRequest', -'Organization', -'OrganizationsClient', -'Project', -'ProjectsClient', -'SearchFoldersRequest', -'SearchFoldersResponse', -'SearchOrganizationsRequest', -'SearchOrganizationsResponse', -'SearchProjectsRequest', -'SearchProjectsResponse', -'TagBinding', -'TagBindingsClient', -'TagKey', -'TagKeysClient', -'TagValue', -'TagValuesClient', -'UndeleteFolderMetadata', -'UndeleteFolderRequest', -'UndeleteOrganizationMetadata', -'UndeleteProjectMetadata', -'UndeleteProjectRequest', -'UpdateFolderMetadata', -'UpdateFolderRequest', -'UpdateProjectMetadata', -'UpdateProjectRequest', -'UpdateTagKeyMetadata', -'UpdateTagKeyRequest', -'UpdateTagValueMetadata', -'UpdateTagValueRequest', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json deleted file mode 100644 index b1415c1..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_metadata.json +++ /dev/null @@ -1,813 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.resourcemanager_v3", - "protoPackage": "google.cloud.resourcemanager.v3", - "schema": "1.0", - "services": { - "Folders": { - "clients": { - "grpc": { - "libraryClient": "FoldersClient", - "rpcs": { - "CreateFolder": { - "methods": [ - "create_folder" - ] - }, - "DeleteFolder": { - "methods": [ - "delete_folder" - ] - }, - "GetFolder": { - "methods": [ - "get_folder" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFolders": { - "methods": [ - "list_folders" - ] - }, - "MoveFolder": { - "methods": [ - "move_folder" - ] - }, - "SearchFolders": { - "methods": [ - "search_folders" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UndeleteFolder": { - "methods": [ - "undelete_folder" - ] - }, - "UpdateFolder": { - "methods": [ - "update_folder" - ] - } - } - }, - "grpc-async": { - "libraryClient": "FoldersAsyncClient", - "rpcs": { - "CreateFolder": { - "methods": [ - "create_folder" - ] - }, - "DeleteFolder": { - "methods": [ - "delete_folder" - ] - }, - "GetFolder": { - "methods": [ - "get_folder" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFolders": { - "methods": [ - "list_folders" - ] - }, - "MoveFolder": { - "methods": [ - "move_folder" - ] - }, - "SearchFolders": { - "methods": [ - "search_folders" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UndeleteFolder": { - "methods": [ - "undelete_folder" - ] - }, - "UpdateFolder": { - "methods": [ - "update_folder" - ] - } - } - }, - "rest": { - "libraryClient": "FoldersClient", - "rpcs": { - "CreateFolder": { - "methods": [ - "create_folder" - ] - }, - "DeleteFolder": { - "methods": [ - "delete_folder" - ] - }, - "GetFolder": { - "methods": [ - "get_folder" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListFolders": { - "methods": [ - "list_folders" - ] - }, - "MoveFolder": { - "methods": [ - "move_folder" - ] - }, - "SearchFolders": { - "methods": [ - "search_folders" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UndeleteFolder": { - "methods": [ - "undelete_folder" - ] - }, - "UpdateFolder": { - "methods": [ - "update_folder" - ] - } - } - } - } - }, - "Organizations": { - "clients": { - "grpc": { - "libraryClient": "OrganizationsClient", - "rpcs": { - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganization": { - "methods": [ - "get_organization" - ] - }, - "SearchOrganizations": { - "methods": [ - "search_organizations" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OrganizationsAsyncClient", - "rpcs": { - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganization": { - "methods": [ - "get_organization" - ] - }, - "SearchOrganizations": { - "methods": [ - "search_organizations" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - } - } - }, - "rest": { - "libraryClient": "OrganizationsClient", - "rpcs": { - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganization": { - "methods": [ - "get_organization" - ] - }, - "SearchOrganizations": { - "methods": [ - "search_organizations" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - } - } - } - } - }, - "Projects": { - "clients": { - "grpc": { - "libraryClient": "ProjectsClient", - "rpcs": { - "CreateProject": { - "methods": [ - "create_project" - ] - }, - "DeleteProject": { - "methods": [ - "delete_project" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetProject": { - "methods": [ - "get_project" - ] - }, - "ListProjects": { - "methods": [ - "list_projects" - ] - }, - "MoveProject": { - "methods": [ - "move_project" - ] - }, - "SearchProjects": { - "methods": [ - "search_projects" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UndeleteProject": { - "methods": [ - "undelete_project" - ] - }, - "UpdateProject": { - "methods": [ - "update_project" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProjectsAsyncClient", - "rpcs": { - "CreateProject": { - "methods": [ - "create_project" - ] - }, - "DeleteProject": { - "methods": [ - "delete_project" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetProject": { - "methods": [ - "get_project" - ] - }, - "ListProjects": { - "methods": [ - "list_projects" - ] - }, - "MoveProject": { - "methods": [ - "move_project" - ] - }, - "SearchProjects": { - "methods": [ - "search_projects" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UndeleteProject": { - "methods": [ - "undelete_project" - ] - }, - "UpdateProject": { - "methods": [ - "update_project" - ] - } - } - }, - "rest": { - "libraryClient": "ProjectsClient", - "rpcs": { - "CreateProject": { - "methods": [ - "create_project" - ] - }, - "DeleteProject": { - "methods": [ - "delete_project" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetProject": { - "methods": [ - "get_project" - ] - }, - "ListProjects": { - "methods": [ - "list_projects" - ] - }, - "MoveProject": { - "methods": [ - "move_project" - ] - }, - "SearchProjects": { - "methods": [ - "search_projects" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UndeleteProject": { - "methods": [ - "undelete_project" - ] - }, - "UpdateProject": { - "methods": [ - "update_project" - ] - } - } - } - } - }, - "TagBindings": { - "clients": { - "grpc": { - "libraryClient": "TagBindingsClient", - "rpcs": { - "CreateTagBinding": { - "methods": [ - "create_tag_binding" - ] - }, - "DeleteTagBinding": { - "methods": [ - "delete_tag_binding" - ] - }, - "ListTagBindings": { - "methods": [ - "list_tag_bindings" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TagBindingsAsyncClient", - "rpcs": { - "CreateTagBinding": { - "methods": [ - "create_tag_binding" - ] - }, - "DeleteTagBinding": { - "methods": [ - "delete_tag_binding" - ] - }, - "ListTagBindings": { - "methods": [ - "list_tag_bindings" - ] - } - } - }, - "rest": { - "libraryClient": "TagBindingsClient", - "rpcs": { - "CreateTagBinding": { - "methods": [ - "create_tag_binding" - ] - }, - "DeleteTagBinding": { - "methods": [ - "delete_tag_binding" - ] - }, - "ListTagBindings": { - "methods": [ - "list_tag_bindings" - ] - } - } - } - } - }, - "TagKeys": { - "clients": { - "grpc": { - "libraryClient": "TagKeysClient", - "rpcs": { - "CreateTagKey": { - "methods": [ - "create_tag_key" - ] - }, - "DeleteTagKey": { - "methods": [ - "delete_tag_key" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagKey": { - "methods": [ - "get_tag_key" - ] - }, - "ListTagKeys": { - "methods": [ - "list_tag_keys" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateTagKey": { - "methods": [ - "update_tag_key" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TagKeysAsyncClient", - "rpcs": { - "CreateTagKey": { - "methods": [ - "create_tag_key" - ] - }, - "DeleteTagKey": { - "methods": [ - "delete_tag_key" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagKey": { - "methods": [ - "get_tag_key" - ] - }, - "ListTagKeys": { - "methods": [ - "list_tag_keys" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateTagKey": { - "methods": [ - "update_tag_key" - ] - } - } - }, - "rest": { - "libraryClient": "TagKeysClient", - "rpcs": { - "CreateTagKey": { - "methods": [ - "create_tag_key" - ] - }, - "DeleteTagKey": { - "methods": [ - "delete_tag_key" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagKey": { - "methods": [ - "get_tag_key" - ] - }, - "ListTagKeys": { - "methods": [ - "list_tag_keys" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateTagKey": { - "methods": [ - "update_tag_key" - ] - } - } - } - } - }, - "TagValues": { - "clients": { - "grpc": { - "libraryClient": "TagValuesClient", - "rpcs": { - "CreateTagValue": { - "methods": [ - "create_tag_value" - ] - }, - "DeleteTagValue": { - "methods": [ - "delete_tag_value" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagValue": { - "methods": [ - "get_tag_value" - ] - }, - "ListTagValues": { - "methods": [ - "list_tag_values" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateTagValue": { - "methods": [ - "update_tag_value" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TagValuesAsyncClient", - "rpcs": { - "CreateTagValue": { - "methods": [ - "create_tag_value" - ] - }, - "DeleteTagValue": { - "methods": [ - "delete_tag_value" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagValue": { - "methods": [ - "get_tag_value" - ] - }, - "ListTagValues": { - "methods": [ - "list_tag_values" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateTagValue": { - "methods": [ - "update_tag_value" - ] - } - } - }, - "rest": { - "libraryClient": "TagValuesClient", - "rpcs": { - "CreateTagValue": { - "methods": [ - "create_tag_value" - ] - }, - "DeleteTagValue": { - "methods": [ - "delete_tag_value" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetTagValue": { - "methods": [ - "get_tag_value" - ] - }, - "ListTagValues": { - "methods": [ - "list_tag_values" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateTagValue": { - "methods": [ - "update_tag_value" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed deleted file mode 100644 index b1e13d7..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-resource-manager package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py deleted file mode 100644 index eeb7430..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import FoldersClient -from .async_client import FoldersAsyncClient - -__all__ = ( - 'FoldersClient', - 'FoldersAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py deleted file mode 100644 index f9886b3..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/async_client.py +++ /dev/null @@ -1,1724 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.folders import pagers -from google.cloud.resourcemanager_v3.types import folders -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FoldersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FoldersGrpcAsyncIOTransport -from .client import FoldersClient - - -class FoldersAsyncClient: - """Manages Cloud Platform folder resources. - Folders can be used to organize the resources under an - organization and to control the policies applied to groups of - resources. - """ - - _client: FoldersClient - - DEFAULT_ENDPOINT = FoldersClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FoldersClient.DEFAULT_MTLS_ENDPOINT - - folder_path = staticmethod(FoldersClient.folder_path) - parse_folder_path = staticmethod(FoldersClient.parse_folder_path) - common_billing_account_path = staticmethod(FoldersClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FoldersClient.parse_common_billing_account_path) - common_folder_path = staticmethod(FoldersClient.common_folder_path) - parse_common_folder_path = staticmethod(FoldersClient.parse_common_folder_path) - common_organization_path = staticmethod(FoldersClient.common_organization_path) - parse_common_organization_path = staticmethod(FoldersClient.parse_common_organization_path) - common_project_path = staticmethod(FoldersClient.common_project_path) - parse_common_project_path = staticmethod(FoldersClient.parse_common_project_path) - common_location_path = staticmethod(FoldersClient.common_location_path) - parse_common_location_path = staticmethod(FoldersClient.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: - FoldersAsyncClient: The constructed client. - """ - return FoldersClient.from_service_account_info.__func__(FoldersAsyncClient, 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: - FoldersAsyncClient: The constructed client. - """ - return FoldersClient.from_service_account_file.__func__(FoldersAsyncClient, 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 FoldersClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> FoldersTransport: - """Returns the transport used by the client instance. - - Returns: - FoldersTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(FoldersClient).get_transport_class, type(FoldersClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FoldersTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the folders client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.FoldersTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = FoldersClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_folder(self, - request: Optional[Union[folders.GetFolderRequest, 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]] = (), - ) -> folders.Folder: - r"""Retrieves a folder identified by the supplied resource name. - Valid folder resource names have the format - ``folders/{folder_id}`` (for example, ``folders/1234``). The - caller must have ``resourcemanager.folders.get`` permission on - the identified 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 resourcemanager_v3 - - async def sample_get_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetFolderRequest( - name="name_value", - ) - - # Make the request - response = await client.get_folder(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.GetFolderRequest, dict]]): - The request object. The GetFolder request message. - name (:class:`str`): - Required. The resource name of the folder to retrieve. - Must be of the form ``folders/{folder_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.resourcemanager_v3.types.Folder: - A folder in an organization's - resource hierarchy, used to organize - that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.GetFolderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_folder, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_folders(self, - request: Optional[Union[folders.ListFoldersRequest, 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.ListFoldersAsyncPager: - r"""Lists the folders that are direct descendants of supplied parent - resource. ``list()`` provides a strongly consistent view of the - folders underneath the specified parent resource. ``list()`` - returns folders sorted based upon the (ascending) lexical - ordering of their display_name. The caller must have - ``resourcemanager.folders.list`` permission on the identified - parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_list_folders(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListFoldersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_folders(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.ListFoldersRequest, dict]]): - The request object. The ListFolders request message. - parent (:class:`str`): - Required. The resource name of the organization or - folder whose folders are being listed. Must be of the - form ``folders/{folder_id}`` or - ``organizations/{org_id}``. Access to this method is - controlled by checking the - ``resourcemanager.folders.list`` permission on the - ``parent``. - - 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.resourcemanager_v3.services.folders.pagers.ListFoldersAsyncPager: - The ListFolders response message. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.ListFoldersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_folders, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListFoldersAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_folders(self, - request: Optional[Union[folders.SearchFoldersRequest, dict]] = None, - *, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchFoldersAsyncPager: - r"""Search for folders that match specific filter criteria. - ``search()`` provides an eventually consistent view of the - folders a user has access to which meet the specified filter - criteria. - - This will only return folders on which the caller has the - permission ``resourcemanager.folders.get``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_search_folders(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchFoldersRequest( - ) - - # Make the request - page_result = client.search_folders(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchFoldersRequest, dict]]): - The request object. The request message for searching - folders. - query (:class:`str`): - Optional. Search criteria used to select the folders to - return. If no search criteria is specified then all - accessible folders will be returned. - - Query expressions can be used to restrict results based - upon displayName, state and parent, where the operators - ``=`` (``:``) ``NOT``, ``AND`` and ``OR`` can be used - along with the suffix wildcard symbol ``*``. - - The ``displayName`` field in a query expression should - use escaped quotes for values that include whitespace to - prevent unexpected behavior. - - :: - - | Field | Description | - |-------------------------|----------------------------------------| - | displayName | Filters by displayName. | - | parent | Filters by parent (for example: folders/123). | - | state, lifecycleState | Filters by state. | - - Some example queries are: - - - Query ``displayName=Test*`` returns Folder resources - whose display name starts with "Test". - - Query ``state=ACTIVE`` returns Folder resources with - ``state`` set to ``ACTIVE``. - - Query ``parent=folders/123`` returns Folder resources - that have ``folders/123`` as a parent resource. - - Query ``parent=folders/123 AND state=ACTIVE`` returns - active Folder resources that have ``folders/123`` as - a parent resource. - - Query ``displayName=\\"Test String\\"`` returns - Folder resources with display names that include both - "Test" and "String". - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersAsyncPager: - The response message for searching - folders. - 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([query]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.SearchFoldersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_folders, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.SearchFoldersAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_folder(self, - request: Optional[Union[folders.CreateFolderRequest, dict]] = None, - *, - folder: Optional[folders.Folder] = 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 folder in the resource hierarchy. Returns an - ``Operation`` which can be used to track the progress of the - folder creation workflow. Upon success, the - ``Operation.response`` field will be populated with the created - Folder. - - In order to succeed, the addition of this new folder must not - violate the folder naming, height, or fanout constraints. - - - The folder's ``display_name`` must be distinct from all other - folders that share its parent. - - The addition of the folder must not cause the active folder - hierarchy to exceed a height of 10. Note, the full active + - deleted folder hierarchy is allowed to reach a height of 20; - this provides additional headroom when moving folders that - contain deleted folders. - - The addition of the folder must not cause the total number of - folders under its parent to exceed 300. - - If the operation fails due to a folder constraint violation, - some errors may be returned by the ``CreateFolder`` request, - with status code ``FAILED_PRECONDITION`` and an error - description. Other folder constraint violations will be - communicated in the ``Operation``, with the specific - ``PreconditionFailure`` returned in the details list in the - ``Operation.error`` field. - - The caller must have ``resourcemanager.folders.create`` - permission on the identified parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_create_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.CreateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.create_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateFolderRequest, dict]]): - The request object. The CreateFolder request message. - folder (:class:`google.cloud.resourcemanager_v3.types.Folder`): - Required. The folder being created, - only the display name and parent will be - consulted. All other fields will be - ignored. - - This corresponds to the ``folder`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([folder]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.CreateFolderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if folder is not None: - request.folder = folder - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_folder, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - folders.Folder, - metadata_type=folders.CreateFolderMetadata, - ) - - # Done; return the response. - return response - - async def update_folder(self, - request: Optional[Union[folders.UpdateFolderRequest, dict]] = None, - *, - folder: Optional[folders.Folder] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates a folder, changing its ``display_name``. Changes to the - folder ``display_name`` will be rejected if they violate either - the ``display_name`` formatting rules or the naming constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. - - The folder's ``display_name`` must start and end with a letter - or digit, may contain letters, digits, spaces, hyphens and - underscores and can be between 3 and 30 characters. This is - captured by the regular expression: - ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller - must have ``resourcemanager.folders.update`` permission on the - identified folder. - - If the update fails due to the unique name constraint then a - ``PreconditionFailure`` explaining this violation will be - returned in the Status.details field. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_update_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.UpdateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.update_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateFolderRequest, dict]]): - The request object. The request sent to the - [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] - method. - - Only the ``display_name`` field can be changed. All - other fields will be ignored. Use the - [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] - method to change the ``parent`` field. - folder (:class:`google.cloud.resourcemanager_v3.types.Folder`): - Required. The new definition of the Folder. It must - include the ``name`` field, which cannot be changed. - - This corresponds to the ``folder`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Fields to be updated. Only the - ``display_name`` can be updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([folder, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.UpdateFolderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if folder is not None: - request.folder = folder - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_folder, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("folder.name", request.folder.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - folders.Folder, - metadata_type=folders.UpdateFolderMetadata, - ) - - # Done; return the response. - return response - - async def move_folder(self, - request: Optional[Union[folders.MoveFolderRequest, dict]] = None, - *, - name: Optional[str] = None, - destination_parent: 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"""Moves a folder under a new resource parent. Returns an - ``Operation`` which can be used to track the progress of the - folder move workflow. Upon success, the ``Operation.response`` - field will be populated with the moved folder. Upon failure, a - ``FolderOperationError`` categorizing the failure cause will be - returned - if the failure occurs synchronously then the - ``FolderOperationError`` will be returned in the - ``Status.details`` field. If it occurs asynchronously, then the - FolderOperation will be returned in the ``Operation.error`` - field. In addition, the ``Operation.metadata`` field will be - populated with a ``FolderOperation`` message as an aid to - stateless clients. Folder moves will be rejected if they violate - either the naming, height, or fanout constraints described in - the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.move`` permission on the folder's - current and proposed new parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_move_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveFolderRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.MoveFolderRequest, dict]]): - The request object. The MoveFolder request message. - name (:class:`str`): - Required. The resource name of the Folder to move. Must - be of the form folders/{folder_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - destination_parent (:class:`str`): - Required. The resource name of the folder or - organization which should be the folder's new parent. - Must be of the form ``folders/{folder_id}`` or - ``organizations/{org_id}``. - - This corresponds to the ``destination_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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick 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, destination_parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.MoveFolderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if destination_parent is not None: - request.destination_parent = destination_parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.move_folder, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - folders.Folder, - metadata_type=folders.MoveFolderMetadata, - ) - - # Done; return the response. - return response - - async def delete_folder(self, - request: Optional[Union[folders.DeleteFolderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Requests deletion of a folder. The folder is moved into the - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state immediately, and is deleted approximately 30 days later. - This method may only be called on an empty folder, where a - folder is empty if it doesn't contain any folders or projects in - the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. If called on a folder in - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state the operation will result in a no-op success. The caller - must have ``resourcemanager.folders.delete`` permission on the - identified 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 resourcemanager_v3 - - async def sample_delete_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteFolderRequest, dict]]): - The request object. The DeleteFolder request message. - name (:class:`str`): - Required. The resource name of the folder to be deleted. - Must be of the form ``folders/{folder_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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.DeleteFolderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_folder, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - folders.Folder, - metadata_type=folders.DeleteFolderMetadata, - ) - - # Done; return the response. - return response - - async def undelete_folder(self, - request: Optional[Union[folders.UndeleteFolderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Cancels the deletion request for a folder. This method may be - called on a folder in any state. If the folder is in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state the result will be a no-op success. In order to succeed, - the folder's parent must be in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. In addition, reintroducing the folder into the tree must - not violate folder naming, height, and fanout constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.undelete`` permission on the - identified 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 resourcemanager_v3 - - async def sample_undelete_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.UndeleteFolderRequest, dict]]): - The request object. The UndeleteFolder request message. - name (:class:`str`): - Required. The resource name of the folder to undelete. - Must be of the form ``folders/{folder_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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = folders.UndeleteFolderRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.undelete_folder, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - folders.Folder, - metadata_type=folders.UndeleteFolderMetadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for a folder. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the folder's resource name, for - example: "folders/1234". The caller must have - ``resourcemanager.folders.getIamPolicy`` permission on the - identified 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 resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on a folder, replacing any - existing policy. The ``resource`` field should be the folder's - resource name, for example: "folders/1234". The caller must have - ``resourcemanager.folders.setIamPolicy`` permission on the - identified 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 resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified folder. - The ``resource`` field should be the folder's resource name, for - example: "folders/1234". - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FoldersAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py deleted file mode 100644 index e566613..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/client.py +++ /dev/null @@ -1,1909 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.folders import pagers -from google.cloud.resourcemanager_v3.types import folders -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FoldersTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FoldersGrpcTransport -from .transports.grpc_asyncio import FoldersGrpcAsyncIOTransport -from .transports.rest import FoldersRestTransport - - -class FoldersClientMeta(type): - """Metaclass for the Folders 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[FoldersTransport]] - _transport_registry["grpc"] = FoldersGrpcTransport - _transport_registry["grpc_asyncio"] = FoldersGrpcAsyncIOTransport - _transport_registry["rest"] = FoldersRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[FoldersTransport]: - """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 FoldersClient(metaclass=FoldersClientMeta): - """Manages Cloud Platform folder resources. - Folders can be used to organize the resources under an - organization and to control the policies applied to groups of - resources. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - FoldersClient: 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: - FoldersClient: 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) -> FoldersTransport: - """Returns the transport used by the client instance. - - Returns: - FoldersTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def folder_path(folder: str,) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_folder_path(path: str) -> Dict[str,str]: - """Parses a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, FoldersTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the folders client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, FoldersTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, FoldersTransport): - # transport is a FoldersTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_folder(self, - request: Optional[Union[folders.GetFolderRequest, 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]] = (), - ) -> folders.Folder: - r"""Retrieves a folder identified by the supplied resource name. - Valid folder resource names have the format - ``folders/{folder_id}`` (for example, ``folders/1234``). The - caller must have ``resourcemanager.folders.get`` permission on - the identified 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 resourcemanager_v3 - - def sample_get_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetFolderRequest( - name="name_value", - ) - - # Make the request - response = client.get_folder(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.GetFolderRequest, dict]): - The request object. The GetFolder request message. - name (str): - Required. The resource name of the folder to retrieve. - Must be of the form ``folders/{folder_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.resourcemanager_v3.types.Folder: - A folder in an organization's - resource hierarchy, used to organize - that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.GetFolderRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.GetFolderRequest): - request = folders.GetFolderRequest(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_folder] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_folders(self, - request: Optional[Union[folders.ListFoldersRequest, 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.ListFoldersPager: - r"""Lists the folders that are direct descendants of supplied parent - resource. ``list()`` provides a strongly consistent view of the - folders underneath the specified parent resource. ``list()`` - returns folders sorted based upon the (ascending) lexical - ordering of their display_name. The caller must have - ``resourcemanager.folders.list`` permission on the identified - parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_list_folders(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListFoldersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_folders(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.ListFoldersRequest, dict]): - The request object. The ListFolders request message. - parent (str): - Required. The resource name of the organization or - folder whose folders are being listed. Must be of the - form ``folders/{folder_id}`` or - ``organizations/{org_id}``. Access to this method is - controlled by checking the - ``resourcemanager.folders.list`` permission on the - ``parent``. - - 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.resourcemanager_v3.services.folders.pagers.ListFoldersPager: - The ListFolders response message. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.ListFoldersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.ListFoldersRequest): - request = folders.ListFoldersRequest(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_folders] - - # 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.ListFoldersPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_folders(self, - request: Optional[Union[folders.SearchFoldersRequest, dict]] = None, - *, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchFoldersPager: - r"""Search for folders that match specific filter criteria. - ``search()`` provides an eventually consistent view of the - folders a user has access to which meet the specified filter - criteria. - - This will only return folders on which the caller has the - permission ``resourcemanager.folders.get``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_search_folders(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchFoldersRequest( - ) - - # Make the request - page_result = client.search_folders(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.SearchFoldersRequest, dict]): - The request object. The request message for searching - folders. - query (str): - Optional. Search criteria used to select the folders to - return. If no search criteria is specified then all - accessible folders will be returned. - - Query expressions can be used to restrict results based - upon displayName, state and parent, where the operators - ``=`` (``:``) ``NOT``, ``AND`` and ``OR`` can be used - along with the suffix wildcard symbol ``*``. - - The ``displayName`` field in a query expression should - use escaped quotes for values that include whitespace to - prevent unexpected behavior. - - :: - - | Field | Description | - |-------------------------|----------------------------------------| - | displayName | Filters by displayName. | - | parent | Filters by parent (for example: folders/123). | - | state, lifecycleState | Filters by state. | - - Some example queries are: - - - Query ``displayName=Test*`` returns Folder resources - whose display name starts with "Test". - - Query ``state=ACTIVE`` returns Folder resources with - ``state`` set to ``ACTIVE``. - - Query ``parent=folders/123`` returns Folder resources - that have ``folders/123`` as a parent resource. - - Query ``parent=folders/123 AND state=ACTIVE`` returns - active Folder resources that have ``folders/123`` as - a parent resource. - - Query ``displayName=\\"Test String\\"`` returns - Folder resources with display names that include both - "Test" and "String". - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersPager: - The response message for searching - folders. - 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([query]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.SearchFoldersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.SearchFoldersRequest): - request = folders.SearchFoldersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_folders] - - # 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.SearchFoldersPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_folder(self, - request: Optional[Union[folders.CreateFolderRequest, dict]] = None, - *, - folder: Optional[folders.Folder] = 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 folder in the resource hierarchy. Returns an - ``Operation`` which can be used to track the progress of the - folder creation workflow. Upon success, the - ``Operation.response`` field will be populated with the created - Folder. - - In order to succeed, the addition of this new folder must not - violate the folder naming, height, or fanout constraints. - - - The folder's ``display_name`` must be distinct from all other - folders that share its parent. - - The addition of the folder must not cause the active folder - hierarchy to exceed a height of 10. Note, the full active + - deleted folder hierarchy is allowed to reach a height of 20; - this provides additional headroom when moving folders that - contain deleted folders. - - The addition of the folder must not cause the total number of - folders under its parent to exceed 300. - - If the operation fails due to a folder constraint violation, - some errors may be returned by the ``CreateFolder`` request, - with status code ``FAILED_PRECONDITION`` and an error - description. Other folder constraint violations will be - communicated in the ``Operation``, with the specific - ``PreconditionFailure`` returned in the details list in the - ``Operation.error`` field. - - The caller must have ``resourcemanager.folders.create`` - permission on the identified parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_create_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.CreateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.create_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.CreateFolderRequest, dict]): - The request object. The CreateFolder request message. - folder (google.cloud.resourcemanager_v3.types.Folder): - Required. The folder being created, - only the display name and parent will be - consulted. All other fields will be - ignored. - - This corresponds to the ``folder`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([folder]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.CreateFolderRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.CreateFolderRequest): - request = folders.CreateFolderRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if folder is not None: - request.folder = folder - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_folder] - - # 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, - folders.Folder, - metadata_type=folders.CreateFolderMetadata, - ) - - # Done; return the response. - return response - - def update_folder(self, - request: Optional[Union[folders.UpdateFolderRequest, dict]] = None, - *, - folder: Optional[folders.Folder] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates a folder, changing its ``display_name``. Changes to the - folder ``display_name`` will be rejected if they violate either - the ``display_name`` formatting rules or the naming constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. - - The folder's ``display_name`` must start and end with a letter - or digit, may contain letters, digits, spaces, hyphens and - underscores and can be between 3 and 30 characters. This is - captured by the regular expression: - ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller - must have ``resourcemanager.folders.update`` permission on the - identified folder. - - If the update fails due to the unique name constraint then a - ``PreconditionFailure`` explaining this violation will be - returned in the Status.details field. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_update_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.UpdateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.update_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.UpdateFolderRequest, dict]): - The request object. The request sent to the - [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] - method. - - Only the ``display_name`` field can be changed. All - other fields will be ignored. Use the - [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] - method to change the ``parent`` field. - folder (google.cloud.resourcemanager_v3.types.Folder): - Required. The new definition of the Folder. It must - include the ``name`` field, which cannot be changed. - - This corresponds to the ``folder`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Fields to be updated. Only the - ``display_name`` can be updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([folder, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.UpdateFolderRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.UpdateFolderRequest): - request = folders.UpdateFolderRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if folder is not None: - request.folder = folder - 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_folder] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("folder.name", request.folder.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - folders.Folder, - metadata_type=folders.UpdateFolderMetadata, - ) - - # Done; return the response. - return response - - def move_folder(self, - request: Optional[Union[folders.MoveFolderRequest, dict]] = None, - *, - name: Optional[str] = None, - destination_parent: 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"""Moves a folder under a new resource parent. Returns an - ``Operation`` which can be used to track the progress of the - folder move workflow. Upon success, the ``Operation.response`` - field will be populated with the moved folder. Upon failure, a - ``FolderOperationError`` categorizing the failure cause will be - returned - if the failure occurs synchronously then the - ``FolderOperationError`` will be returned in the - ``Status.details`` field. If it occurs asynchronously, then the - FolderOperation will be returned in the ``Operation.error`` - field. In addition, the ``Operation.metadata`` field will be - populated with a ``FolderOperation`` message as an aid to - stateless clients. Folder moves will be rejected if they violate - either the naming, height, or fanout constraints described in - the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.move`` permission on the folder's - current and proposed new parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_move_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveFolderRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.MoveFolderRequest, dict]): - The request object. The MoveFolder request message. - name (str): - Required. The resource name of the Folder to move. Must - be of the form folders/{folder_id} - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - destination_parent (str): - Required. The resource name of the folder or - organization which should be the folder's new parent. - Must be of the form ``folders/{folder_id}`` or - ``organizations/{org_id}``. - - This corresponds to the ``destination_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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick 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, destination_parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.MoveFolderRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.MoveFolderRequest): - request = folders.MoveFolderRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if destination_parent is not None: - request.destination_parent = destination_parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.move_folder] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - folders.Folder, - metadata_type=folders.MoveFolderMetadata, - ) - - # Done; return the response. - return response - - def delete_folder(self, - request: Optional[Union[folders.DeleteFolderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Requests deletion of a folder. The folder is moved into the - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state immediately, and is deleted approximately 30 days later. - This method may only be called on an empty folder, where a - folder is empty if it doesn't contain any folders or projects in - the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. If called on a folder in - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state the operation will result in a no-op success. The caller - must have ``resourcemanager.folders.delete`` permission on the - identified 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 resourcemanager_v3 - - def sample_delete_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.DeleteFolderRequest, dict]): - The request object. The DeleteFolder request message. - name (str): - Required. The resource name of the folder to be deleted. - Must be of the form ``folders/{folder_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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.DeleteFolderRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.DeleteFolderRequest): - request = folders.DeleteFolderRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_folder] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - folders.Folder, - metadata_type=folders.DeleteFolderMetadata, - ) - - # Done; return the response. - return response - - def undelete_folder(self, - request: Optional[Union[folders.UndeleteFolderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Cancels the deletion request for a folder. This method may be - called on a folder in any state. If the folder is in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state the result will be a no-op success. In order to succeed, - the folder's parent must be in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. In addition, reintroducing the folder into the tree must - not violate folder naming, height, and fanout constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.undelete`` permission on the - identified 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 resourcemanager_v3 - - def sample_undelete_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.UndeleteFolderRequest, dict]): - The request object. The UndeleteFolder request message. - name (str): - Required. The resource name of the folder to undelete. - Must be of the form ``folders/{folder_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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Folder` A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a folders.UndeleteFolderRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, folders.UndeleteFolderRequest): - request = folders.UndeleteFolderRequest(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.undelete_folder] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - folders.Folder, - metadata_type=folders.UndeleteFolderMetadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for a folder. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the folder's resource name, for - example: "folders/1234". The caller must have - ``resourcemanager.folders.getIamPolicy`` permission on the - identified 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 resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on a folder, replacing any - existing policy. The ``resource`` field should be the folder's - resource name, for example: "folders/1234". The caller must have - ``resourcemanager.folders.setIamPolicy`` permission on the - identified 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 resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified folder. - The ``resource`` field should be the folder's resource name, for - example: "folders/1234". - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "FoldersClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "FoldersClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py deleted file mode 100644 index e4867b9..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.resourcemanager_v3.types import folders - - -class ListFoldersPager: - """A pager for iterating through ``list_folders`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``folders`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFolders`` requests and continue to iterate - through the ``folders`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` - 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[..., folders.ListFoldersResponse], - request: folders.ListFoldersRequest, - response: folders.ListFoldersResponse, - *, - 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.resourcemanager_v3.types.ListFoldersRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListFoldersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = folders.ListFoldersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[folders.ListFoldersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[folders.Folder]: - for page in self.pages: - yield from page.folders - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFoldersAsyncPager: - """A pager for iterating through ``list_folders`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``folders`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFolders`` requests and continue to iterate - through the ``folders`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` - 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[folders.ListFoldersResponse]], - request: folders.ListFoldersRequest, - response: folders.ListFoldersResponse, - *, - 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.resourcemanager_v3.types.ListFoldersRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListFoldersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = folders.ListFoldersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[folders.ListFoldersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[folders.Folder]: - async def async_generator(): - async for page in self.pages: - for response in page.folders: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchFoldersPager: - """A pager for iterating through ``search_folders`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``folders`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchFolders`` requests and continue to iterate - through the ``folders`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` - 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[..., folders.SearchFoldersResponse], - request: folders.SearchFoldersRequest, - response: folders.SearchFoldersResponse, - *, - 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.resourcemanager_v3.types.SearchFoldersRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.SearchFoldersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = folders.SearchFoldersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[folders.SearchFoldersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[folders.Folder]: - for page in self.pages: - yield from page.folders - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchFoldersAsyncPager: - """A pager for iterating through ``search_folders`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``folders`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchFolders`` requests and continue to iterate - through the ``folders`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` - 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[folders.SearchFoldersResponse]], - request: folders.SearchFoldersRequest, - response: folders.SearchFoldersResponse, - *, - 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.resourcemanager_v3.types.SearchFoldersRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.SearchFoldersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = folders.SearchFoldersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[folders.SearchFoldersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[folders.Folder]: - async def async_generator(): - async for page in self.pages: - for response in page.folders: - 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/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py deleted file mode 100644 index 6156c27..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import FoldersTransport -from .grpc import FoldersGrpcTransport -from .grpc_asyncio import FoldersGrpcAsyncIOTransport -from .rest import FoldersRestTransport -from .rest import FoldersRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FoldersTransport]] -_transport_registry['grpc'] = FoldersGrpcTransport -_transport_registry['grpc_asyncio'] = FoldersGrpcAsyncIOTransport -_transport_registry['rest'] = FoldersRestTransport - -__all__ = ( - 'FoldersTransport', - 'FoldersGrpcTransport', - 'FoldersGrpcAsyncIOTransport', - 'FoldersRestTransport', - 'FoldersRestInterceptor', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py deleted file mode 100644 index 3bcb757..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/base.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.resourcemanager_v3 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.resourcemanager_v3.types import folders -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 FoldersTransport(abc.ABC): - """Abstract transport class for Folders.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_folder: gapic_v1.method.wrap_method( - self.get_folder, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_folders: gapic_v1.method.wrap_method( - self.list_folders, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.search_folders: gapic_v1.method.wrap_method( - self.search_folders, - default_timeout=60.0, - client_info=client_info, - ), - self.create_folder: gapic_v1.method.wrap_method( - self.create_folder, - default_timeout=60.0, - client_info=client_info, - ), - self.update_folder: gapic_v1.method.wrap_method( - self.update_folder, - default_timeout=60.0, - client_info=client_info, - ), - self.move_folder: gapic_v1.method.wrap_method( - self.move_folder, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_folder: gapic_v1.method.wrap_method( - self.delete_folder, - default_timeout=60.0, - client_info=client_info, - ), - self.undelete_folder: gapic_v1.method.wrap_method( - self.undelete_folder, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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 get_folder(self) -> Callable[ - [folders.GetFolderRequest], - Union[ - folders.Folder, - Awaitable[folders.Folder] - ]]: - raise NotImplementedError() - - @property - def list_folders(self) -> Callable[ - [folders.ListFoldersRequest], - Union[ - folders.ListFoldersResponse, - Awaitable[folders.ListFoldersResponse] - ]]: - raise NotImplementedError() - - @property - def search_folders(self) -> Callable[ - [folders.SearchFoldersRequest], - Union[ - folders.SearchFoldersResponse, - Awaitable[folders.SearchFoldersResponse] - ]]: - raise NotImplementedError() - - @property - def create_folder(self) -> Callable[ - [folders.CreateFolderRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_folder(self) -> Callable[ - [folders.UpdateFolderRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def move_folder(self) -> Callable[ - [folders.MoveFolderRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_folder(self) -> Callable[ - [folders.DeleteFolderRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undelete_folder(self) -> Callable[ - [folders.UndeleteFolderRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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__ = ( - 'FoldersTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py deleted file mode 100644 index fe8fe0b..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc.py +++ /dev/null @@ -1,662 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.resourcemanager_v3.types import folders -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 FoldersTransport, DEFAULT_CLIENT_INFO - - -class FoldersGrpcTransport(FoldersTransport): - """gRPC backend transport for Folders. - - Manages Cloud Platform folder resources. - Folders can be used to organize the resources under an - organization and to control the policies applied to groups of - resources. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudresourcemanager.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 get_folder(self) -> Callable[ - [folders.GetFolderRequest], - folders.Folder]: - r"""Return a callable for the get folder method over gRPC. - - Retrieves a folder identified by the supplied resource name. - Valid folder resource names have the format - ``folders/{folder_id}`` (for example, ``folders/1234``). The - caller must have ``resourcemanager.folders.get`` permission on - the identified folder. - - Returns: - Callable[[~.GetFolderRequest], - ~.Folder]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_folder' not in self._stubs: - self._stubs['get_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/GetFolder', - request_serializer=folders.GetFolderRequest.serialize, - response_deserializer=folders.Folder.deserialize, - ) - return self._stubs['get_folder'] - - @property - def list_folders(self) -> Callable[ - [folders.ListFoldersRequest], - folders.ListFoldersResponse]: - r"""Return a callable for the list folders method over gRPC. - - Lists the folders that are direct descendants of supplied parent - resource. ``list()`` provides a strongly consistent view of the - folders underneath the specified parent resource. ``list()`` - returns folders sorted based upon the (ascending) lexical - ordering of their display_name. The caller must have - ``resourcemanager.folders.list`` permission on the identified - parent. - - Returns: - Callable[[~.ListFoldersRequest], - ~.ListFoldersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_folders' not in self._stubs: - self._stubs['list_folders'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/ListFolders', - request_serializer=folders.ListFoldersRequest.serialize, - response_deserializer=folders.ListFoldersResponse.deserialize, - ) - return self._stubs['list_folders'] - - @property - def search_folders(self) -> Callable[ - [folders.SearchFoldersRequest], - folders.SearchFoldersResponse]: - r"""Return a callable for the search folders method over gRPC. - - Search for folders that match specific filter criteria. - ``search()`` provides an eventually consistent view of the - folders a user has access to which meet the specified filter - criteria. - - This will only return folders on which the caller has the - permission ``resourcemanager.folders.get``. - - Returns: - Callable[[~.SearchFoldersRequest], - ~.SearchFoldersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_folders' not in self._stubs: - self._stubs['search_folders'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/SearchFolders', - request_serializer=folders.SearchFoldersRequest.serialize, - response_deserializer=folders.SearchFoldersResponse.deserialize, - ) - return self._stubs['search_folders'] - - @property - def create_folder(self) -> Callable[ - [folders.CreateFolderRequest], - operations_pb2.Operation]: - r"""Return a callable for the create folder method over gRPC. - - Creates a folder in the resource hierarchy. Returns an - ``Operation`` which can be used to track the progress of the - folder creation workflow. Upon success, the - ``Operation.response`` field will be populated with the created - Folder. - - In order to succeed, the addition of this new folder must not - violate the folder naming, height, or fanout constraints. - - - The folder's ``display_name`` must be distinct from all other - folders that share its parent. - - The addition of the folder must not cause the active folder - hierarchy to exceed a height of 10. Note, the full active + - deleted folder hierarchy is allowed to reach a height of 20; - this provides additional headroom when moving folders that - contain deleted folders. - - The addition of the folder must not cause the total number of - folders under its parent to exceed 300. - - If the operation fails due to a folder constraint violation, - some errors may be returned by the ``CreateFolder`` request, - with status code ``FAILED_PRECONDITION`` and an error - description. Other folder constraint violations will be - communicated in the ``Operation``, with the specific - ``PreconditionFailure`` returned in the details list in the - ``Operation.error`` field. - - The caller must have ``resourcemanager.folders.create`` - permission on the identified parent. - - Returns: - Callable[[~.CreateFolderRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_folder' not in self._stubs: - self._stubs['create_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/CreateFolder', - request_serializer=folders.CreateFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_folder'] - - @property - def update_folder(self) -> Callable[ - [folders.UpdateFolderRequest], - operations_pb2.Operation]: - r"""Return a callable for the update folder method over gRPC. - - Updates a folder, changing its ``display_name``. Changes to the - folder ``display_name`` will be rejected if they violate either - the ``display_name`` formatting rules or the naming constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. - - The folder's ``display_name`` must start and end with a letter - or digit, may contain letters, digits, spaces, hyphens and - underscores and can be between 3 and 30 characters. This is - captured by the regular expression: - ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller - must have ``resourcemanager.folders.update`` permission on the - identified folder. - - If the update fails due to the unique name constraint then a - ``PreconditionFailure`` explaining this violation will be - returned in the Status.details field. - - Returns: - Callable[[~.UpdateFolderRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_folder' not in self._stubs: - self._stubs['update_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/UpdateFolder', - request_serializer=folders.UpdateFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_folder'] - - @property - def move_folder(self) -> Callable[ - [folders.MoveFolderRequest], - operations_pb2.Operation]: - r"""Return a callable for the move folder method over gRPC. - - Moves a folder under a new resource parent. Returns an - ``Operation`` which can be used to track the progress of the - folder move workflow. Upon success, the ``Operation.response`` - field will be populated with the moved folder. Upon failure, a - ``FolderOperationError`` categorizing the failure cause will be - returned - if the failure occurs synchronously then the - ``FolderOperationError`` will be returned in the - ``Status.details`` field. If it occurs asynchronously, then the - FolderOperation will be returned in the ``Operation.error`` - field. In addition, the ``Operation.metadata`` field will be - populated with a ``FolderOperation`` message as an aid to - stateless clients. Folder moves will be rejected if they violate - either the naming, height, or fanout constraints described in - the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.move`` permission on the folder's - current and proposed new parent. - - Returns: - Callable[[~.MoveFolderRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'move_folder' not in self._stubs: - self._stubs['move_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/MoveFolder', - request_serializer=folders.MoveFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['move_folder'] - - @property - def delete_folder(self) -> Callable[ - [folders.DeleteFolderRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete folder method over gRPC. - - Requests deletion of a folder. The folder is moved into the - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state immediately, and is deleted approximately 30 days later. - This method may only be called on an empty folder, where a - folder is empty if it doesn't contain any folders or projects in - the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. If called on a folder in - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state the operation will result in a no-op success. The caller - must have ``resourcemanager.folders.delete`` permission on the - identified folder. - - Returns: - Callable[[~.DeleteFolderRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_folder' not in self._stubs: - self._stubs['delete_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/DeleteFolder', - request_serializer=folders.DeleteFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_folder'] - - @property - def undelete_folder(self) -> Callable[ - [folders.UndeleteFolderRequest], - operations_pb2.Operation]: - r"""Return a callable for the undelete folder method over gRPC. - - Cancels the deletion request for a folder. This method may be - called on a folder in any state. If the folder is in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state the result will be a no-op success. In order to succeed, - the folder's parent must be in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. In addition, reintroducing the folder into the tree must - not violate folder naming, height, and fanout constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.undelete`` permission on the - identified folder. - - Returns: - Callable[[~.UndeleteFolderRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undelete_folder' not in self._stubs: - self._stubs['undelete_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/UndeleteFolder', - request_serializer=folders.UndeleteFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undelete_folder'] - - @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 access control policy for a folder. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the folder's resource name, for - example: "folders/1234". The caller must have - ``resourcemanager.folders.getIamPolicy`` permission on the - identified folder. - - 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.cloud.resourcemanager.v3.Folders/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on a folder, replacing any - existing policy. The ``resource`` field should be the folder's - resource name, for example: "folders/1234". The caller must have - ``resourcemanager.folders.setIamPolicy`` permission on the - identified folder. - - 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.cloud.resourcemanager.v3.Folders/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the specified folder. - The ``resource`` field should be the folder's resource name, for - example: "folders/1234". - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.Folders/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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'FoldersGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py deleted file mode 100644 index 0672f47..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py +++ /dev/null @@ -1,661 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.resourcemanager_v3.types import folders -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 FoldersTransport, DEFAULT_CLIENT_INFO -from .grpc import FoldersGrpcTransport - - -class FoldersGrpcAsyncIOTransport(FoldersTransport): - """gRPC AsyncIO backend transport for Folders. - - Manages Cloud Platform folder resources. - Folders can be used to organize the resources under an - organization and to control the policies applied to groups of - resources. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_folder(self) -> Callable[ - [folders.GetFolderRequest], - Awaitable[folders.Folder]]: - r"""Return a callable for the get folder method over gRPC. - - Retrieves a folder identified by the supplied resource name. - Valid folder resource names have the format - ``folders/{folder_id}`` (for example, ``folders/1234``). The - caller must have ``resourcemanager.folders.get`` permission on - the identified folder. - - Returns: - Callable[[~.GetFolderRequest], - Awaitable[~.Folder]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_folder' not in self._stubs: - self._stubs['get_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/GetFolder', - request_serializer=folders.GetFolderRequest.serialize, - response_deserializer=folders.Folder.deserialize, - ) - return self._stubs['get_folder'] - - @property - def list_folders(self) -> Callable[ - [folders.ListFoldersRequest], - Awaitable[folders.ListFoldersResponse]]: - r"""Return a callable for the list folders method over gRPC. - - Lists the folders that are direct descendants of supplied parent - resource. ``list()`` provides a strongly consistent view of the - folders underneath the specified parent resource. ``list()`` - returns folders sorted based upon the (ascending) lexical - ordering of their display_name. The caller must have - ``resourcemanager.folders.list`` permission on the identified - parent. - - Returns: - Callable[[~.ListFoldersRequest], - Awaitable[~.ListFoldersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_folders' not in self._stubs: - self._stubs['list_folders'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/ListFolders', - request_serializer=folders.ListFoldersRequest.serialize, - response_deserializer=folders.ListFoldersResponse.deserialize, - ) - return self._stubs['list_folders'] - - @property - def search_folders(self) -> Callable[ - [folders.SearchFoldersRequest], - Awaitable[folders.SearchFoldersResponse]]: - r"""Return a callable for the search folders method over gRPC. - - Search for folders that match specific filter criteria. - ``search()`` provides an eventually consistent view of the - folders a user has access to which meet the specified filter - criteria. - - This will only return folders on which the caller has the - permission ``resourcemanager.folders.get``. - - Returns: - Callable[[~.SearchFoldersRequest], - Awaitable[~.SearchFoldersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_folders' not in self._stubs: - self._stubs['search_folders'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/SearchFolders', - request_serializer=folders.SearchFoldersRequest.serialize, - response_deserializer=folders.SearchFoldersResponse.deserialize, - ) - return self._stubs['search_folders'] - - @property - def create_folder(self) -> Callable[ - [folders.CreateFolderRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create folder method over gRPC. - - Creates a folder in the resource hierarchy. Returns an - ``Operation`` which can be used to track the progress of the - folder creation workflow. Upon success, the - ``Operation.response`` field will be populated with the created - Folder. - - In order to succeed, the addition of this new folder must not - violate the folder naming, height, or fanout constraints. - - - The folder's ``display_name`` must be distinct from all other - folders that share its parent. - - The addition of the folder must not cause the active folder - hierarchy to exceed a height of 10. Note, the full active + - deleted folder hierarchy is allowed to reach a height of 20; - this provides additional headroom when moving folders that - contain deleted folders. - - The addition of the folder must not cause the total number of - folders under its parent to exceed 300. - - If the operation fails due to a folder constraint violation, - some errors may be returned by the ``CreateFolder`` request, - with status code ``FAILED_PRECONDITION`` and an error - description. Other folder constraint violations will be - communicated in the ``Operation``, with the specific - ``PreconditionFailure`` returned in the details list in the - ``Operation.error`` field. - - The caller must have ``resourcemanager.folders.create`` - permission on the identified parent. - - Returns: - Callable[[~.CreateFolderRequest], - 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_folder' not in self._stubs: - self._stubs['create_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/CreateFolder', - request_serializer=folders.CreateFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_folder'] - - @property - def update_folder(self) -> Callable[ - [folders.UpdateFolderRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update folder method over gRPC. - - Updates a folder, changing its ``display_name``. Changes to the - folder ``display_name`` will be rejected if they violate either - the ``display_name`` formatting rules or the naming constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. - - The folder's ``display_name`` must start and end with a letter - or digit, may contain letters, digits, spaces, hyphens and - underscores and can be between 3 and 30 characters. This is - captured by the regular expression: - ``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller - must have ``resourcemanager.folders.update`` permission on the - identified folder. - - If the update fails due to the unique name constraint then a - ``PreconditionFailure`` explaining this violation will be - returned in the Status.details field. - - Returns: - Callable[[~.UpdateFolderRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_folder' not in self._stubs: - self._stubs['update_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/UpdateFolder', - request_serializer=folders.UpdateFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_folder'] - - @property - def move_folder(self) -> Callable[ - [folders.MoveFolderRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the move folder method over gRPC. - - Moves a folder under a new resource parent. Returns an - ``Operation`` which can be used to track the progress of the - folder move workflow. Upon success, the ``Operation.response`` - field will be populated with the moved folder. Upon failure, a - ``FolderOperationError`` categorizing the failure cause will be - returned - if the failure occurs synchronously then the - ``FolderOperationError`` will be returned in the - ``Status.details`` field. If it occurs asynchronously, then the - FolderOperation will be returned in the ``Operation.error`` - field. In addition, the ``Operation.metadata`` field will be - populated with a ``FolderOperation`` message as an aid to - stateless clients. Folder moves will be rejected if they violate - either the naming, height, or fanout constraints described in - the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.move`` permission on the folder's - current and proposed new parent. - - Returns: - Callable[[~.MoveFolderRequest], - 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 'move_folder' not in self._stubs: - self._stubs['move_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/MoveFolder', - request_serializer=folders.MoveFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['move_folder'] - - @property - def delete_folder(self) -> Callable[ - [folders.DeleteFolderRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete folder method over gRPC. - - Requests deletion of a folder. The folder is moved into the - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state immediately, and is deleted approximately 30 days later. - This method may only be called on an empty folder, where a - folder is empty if it doesn't contain any folders or projects in - the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. If called on a folder in - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state the operation will result in a no-op success. The caller - must have ``resourcemanager.folders.delete`` permission on the - identified folder. - - Returns: - Callable[[~.DeleteFolderRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_folder' not in self._stubs: - self._stubs['delete_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/DeleteFolder', - request_serializer=folders.DeleteFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_folder'] - - @property - def undelete_folder(self) -> Callable[ - [folders.UndeleteFolderRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undelete folder method over gRPC. - - Cancels the deletion request for a folder. This method may be - called on a folder in any state. If the folder is in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state the result will be a no-op success. In order to succeed, - the folder's parent must be in the - [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE] - state. In addition, reintroducing the folder into the tree must - not violate folder naming, height, and fanout constraints - described in the - [CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder] - documentation. The caller must have - ``resourcemanager.folders.undelete`` permission on the - identified folder. - - Returns: - Callable[[~.UndeleteFolderRequest], - 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 'undelete_folder' not in self._stubs: - self._stubs['undelete_folder'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Folders/UndeleteFolder', - request_serializer=folders.UndeleteFolderRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undelete_folder'] - - @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 access control policy for a folder. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the folder's resource name, for - example: "folders/1234". The caller must have - ``resourcemanager.folders.getIamPolicy`` permission on the - identified folder. - - 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.cloud.resourcemanager.v3.Folders/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on a folder, replacing any - existing policy. The ``resource`` field should be the folder's - resource name, for example: "folders/1234". The caller must have - ``resourcemanager.folders.setIamPolicy`` permission on the - identified folder. - - 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.cloud.resourcemanager.v3.Folders/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the specified folder. - The ``resource`` field should be the folder's resource name, for - example: "folders/1234". - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.Folders/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'FoldersGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py deleted file mode 100644 index b45b76a..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/folders/transports/rest.py +++ /dev/null @@ -1,1650 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.resourcemanager_v3.types import folders -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 FoldersTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class FoldersRestInterceptor: - """Interceptor for Folders. - - 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 FoldersRestTransport. - - .. code-block:: python - class MyCustomFoldersInterceptor(FoldersRestInterceptor): - def pre_create_folder(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_folder(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_folder(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_folder(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_folder(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_folder(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_folders(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_folders(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_move_folder(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_move_folder(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_folders(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_folders(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undelete_folder(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undelete_folder(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_folder(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_folder(self, response): - logging.log(f"Received response: {response}") - return response - - transport = FoldersRestTransport(interceptor=MyCustomFoldersInterceptor()) - client = FoldersClient(transport=transport) - - - """ - def pre_create_folder(self, request: folders.CreateFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.CreateFolderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_folder - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_create_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_folder - - Override in a subclass to manipulate the response - after it is returned by the Folders server but before - it is returned to user code. - """ - return response - def pre_delete_folder(self, request: folders.DeleteFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.DeleteFolderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_folder - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_delete_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_folder - - Override in a subclass to manipulate the response - after it is returned by the Folders server but before - it is returned to user code. - """ - return response - def pre_get_folder(self, request: folders.GetFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.GetFolderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_folder - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_get_folder(self, response: folders.Folder) -> folders.Folder: - """Post-rpc interceptor for get_folder - - Override in a subclass to manipulate the response - after it is returned by the Folders 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 Folders 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 Folders server but before - it is returned to user code. - """ - return response - def pre_list_folders(self, request: folders.ListFoldersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.ListFoldersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_folders - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_list_folders(self, response: folders.ListFoldersResponse) -> folders.ListFoldersResponse: - """Post-rpc interceptor for list_folders - - Override in a subclass to manipulate the response - after it is returned by the Folders server but before - it is returned to user code. - """ - return response - def pre_move_folder(self, request: folders.MoveFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.MoveFolderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for move_folder - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_move_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for move_folder - - Override in a subclass to manipulate the response - after it is returned by the Folders server but before - it is returned to user code. - """ - return response - def pre_search_folders(self, request: folders.SearchFoldersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.SearchFoldersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_folders - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_search_folders(self, response: folders.SearchFoldersResponse) -> folders.SearchFoldersResponse: - """Post-rpc interceptor for search_folders - - Override in a subclass to manipulate the response - after it is returned by the Folders 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 Folders 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 Folders 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 Folders 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 Folders server but before - it is returned to user code. - """ - return response - def pre_undelete_folder(self, request: folders.UndeleteFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.UndeleteFolderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undelete_folder - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_undelete_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undelete_folder - - Override in a subclass to manipulate the response - after it is returned by the Folders server but before - it is returned to user code. - """ - return response - def pre_update_folder(self, request: folders.UpdateFolderRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[folders.UpdateFolderRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_folder - - Override in a subclass to manipulate the request or metadata - before they are sent to the Folders server. - """ - return request, metadata - - def post_update_folder(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_folder - - Override in a subclass to manipulate the response - after it is returned by the Folders server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class FoldersRestStub: - _session: AuthorizedSession - _host: str - _interceptor: FoldersRestInterceptor - - -class FoldersRestTransport(FoldersTransport): - """REST backend transport for Folders. - - Manages Cloud Platform folder resources. - Folders can be used to organize the resources under an - organization and to control the policies applied to groups of - resources. - - 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 = 'cloudresourcemanager.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[FoldersRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or FoldersRestInterceptor() - 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': '/v3/{name=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="v3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateFolder(FoldersRestStub): - def __hash__(self): - return hash("CreateFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.CreateFolderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create folder method over HTTP. - - Args: - request (~.folders.CreateFolderRequest): - The request object. The CreateFolder request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/folders', - 'body': 'folder', - }, - ] - request, metadata = self._interceptor.pre_create_folder(request, metadata) - pb_request = folders.CreateFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_folder(resp) - return resp - - class _DeleteFolder(FoldersRestStub): - def __hash__(self): - return hash("DeleteFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.DeleteFolderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete folder method over HTTP. - - Args: - request (~.folders.DeleteFolderRequest): - The request object. The DeleteFolder request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v3/{name=folders/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_folder(request, metadata) - pb_request = folders.DeleteFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_folder(resp) - return resp - - class _GetFolder(FoldersRestStub): - def __hash__(self): - return hash("GetFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.GetFolderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> folders.Folder: - r"""Call the get folder method over HTTP. - - Args: - request (~.folders.GetFolderRequest): - The request object. The GetFolder request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.folders.Folder: - A folder in an organization's - resource hierarchy, used to organize - that organization's resources. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/{name=folders/*}', - }, - ] - request, metadata = self._interceptor.pre_get_folder(request, metadata) - pb_request = folders.GetFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = folders.Folder() - pb_resp = folders.Folder.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_folder(resp) - return resp - - class _GetIamPolicy(FoldersRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=folders/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _ListFolders(FoldersRestStub): - def __hash__(self): - return hash("ListFolders") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.ListFoldersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> folders.ListFoldersResponse: - r"""Call the list folders method over HTTP. - - Args: - request (~.folders.ListFoldersRequest): - The request object. The ListFolders request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.folders.ListFoldersResponse: - The ListFolders response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/folders', - }, - ] - request, metadata = self._interceptor.pre_list_folders(request, metadata) - pb_request = folders.ListFoldersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = folders.ListFoldersResponse() - pb_resp = folders.ListFoldersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_folders(resp) - return resp - - class _MoveFolder(FoldersRestStub): - def __hash__(self): - return hash("MoveFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.MoveFolderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the move folder method over HTTP. - - Args: - request (~.folders.MoveFolderRequest): - The request object. The MoveFolder request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{name=folders/*}:move', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_move_folder(request, metadata) - pb_request = folders.MoveFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_move_folder(resp) - return resp - - class _SearchFolders(FoldersRestStub): - def __hash__(self): - return hash("SearchFolders") - - def __call__(self, - request: folders.SearchFoldersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> folders.SearchFoldersResponse: - r"""Call the search folders method over HTTP. - - Args: - request (~.folders.SearchFoldersRequest): - The request object. The request message for searching - folders. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.folders.SearchFoldersResponse: - The response message for searching - folders. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/folders:search', - }, - ] - request, metadata = self._interceptor.pre_search_folders(request, metadata) - pb_request = folders.SearchFoldersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = folders.SearchFoldersResponse() - pb_resp = folders.SearchFoldersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_folders(resp) - return resp - - class _SetIamPolicy(FoldersRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=folders/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(FoldersRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=folders/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UndeleteFolder(FoldersRestStub): - def __hash__(self): - return hash("UndeleteFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.UndeleteFolderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undelete folder method over HTTP. - - Args: - request (~.folders.UndeleteFolderRequest): - The request object. The UndeleteFolder request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{name=folders/*}:undelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undelete_folder(request, metadata) - pb_request = folders.UndeleteFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undelete_folder(resp) - return resp - - class _UpdateFolder(FoldersRestStub): - def __hash__(self): - return hash("UpdateFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: folders.UpdateFolderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update folder method over HTTP. - - Args: - request (~.folders.UpdateFolderRequest): - The request object. The request sent to the - [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] - method. - - Only the ``display_name`` field can be changed. All - other fields will be ignored. Use the - [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] - method to change the ``parent`` field. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v3/{folder.name=folders/*}', - 'body': 'folder', - }, - ] - request, metadata = self._interceptor.pre_update_folder(request, metadata) - pb_request = folders.UpdateFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_folder(resp) - return resp - - @property - def create_folder(self) -> Callable[ - [folders.CreateFolderRequest], - 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._CreateFolder(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_folder(self) -> Callable[ - [folders.DeleteFolderRequest], - 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._DeleteFolder(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_folder(self) -> Callable[ - [folders.GetFolderRequest], - folders.Folder]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetFolder(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_folders(self) -> Callable[ - [folders.ListFoldersRequest], - folders.ListFoldersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListFolders(self._session, self._host, self._interceptor) # type: ignore - - @property - def move_folder(self) -> Callable[ - [folders.MoveFolderRequest], - 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._MoveFolder(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_folders(self) -> Callable[ - [folders.SearchFoldersRequest], - folders.SearchFoldersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchFolders(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def undelete_folder(self) -> Callable[ - [folders.UndeleteFolderRequest], - 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._UndeleteFolder(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_folder(self) -> Callable[ - [folders.UpdateFolderRequest], - 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._UpdateFolder(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'FoldersRestTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py deleted file mode 100644 index f7d11d1..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import OrganizationsClient -from .async_client import OrganizationsAsyncClient - -__all__ = ( - 'OrganizationsClient', - 'OrganizationsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py deleted file mode 100644 index 2cfc4eb..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/async_client.py +++ /dev/null @@ -1,905 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.resourcemanager_v3.services.organizations import pagers -from google.cloud.resourcemanager_v3.types import organizations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OrganizationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OrganizationsGrpcAsyncIOTransport -from .client import OrganizationsClient - - -class OrganizationsAsyncClient: - """Allows users to manage their organization resources.""" - - _client: OrganizationsClient - - DEFAULT_ENDPOINT = OrganizationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = OrganizationsClient.DEFAULT_MTLS_ENDPOINT - - organization_path = staticmethod(OrganizationsClient.organization_path) - parse_organization_path = staticmethod(OrganizationsClient.parse_organization_path) - common_billing_account_path = staticmethod(OrganizationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OrganizationsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OrganizationsClient.common_folder_path) - parse_common_folder_path = staticmethod(OrganizationsClient.parse_common_folder_path) - common_organization_path = staticmethod(OrganizationsClient.common_organization_path) - parse_common_organization_path = staticmethod(OrganizationsClient.parse_common_organization_path) - common_project_path = staticmethod(OrganizationsClient.common_project_path) - parse_common_project_path = staticmethod(OrganizationsClient.parse_common_project_path) - common_location_path = staticmethod(OrganizationsClient.common_location_path) - parse_common_location_path = staticmethod(OrganizationsClient.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: - OrganizationsAsyncClient: The constructed client. - """ - return OrganizationsClient.from_service_account_info.__func__(OrganizationsAsyncClient, 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: - OrganizationsAsyncClient: The constructed client. - """ - return OrganizationsClient.from_service_account_file.__func__(OrganizationsAsyncClient, 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 OrganizationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> OrganizationsTransport: - """Returns the transport used by the client instance. - - Returns: - OrganizationsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(OrganizationsClient).get_transport_class, type(OrganizationsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, OrganizationsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the organizations client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.OrganizationsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = OrganizationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_organization(self, - request: Optional[Union[organizations.GetOrganizationRequest, 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]] = (), - ) -> organizations.Organization: - r"""Fetches an organization resource identified by the - specified resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_get_organization(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetOrganizationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]]): - The request object. The request sent to the ``GetOrganization`` method. The - ``name`` field is required. ``organization_id`` is no - longer accepted. - name (:class:`str`): - Required. The resource name of the Organization to - fetch. This is the organization's relative path in the - API, formatted as "organizations/[organizationId]". For - example, "organizations/1234". - - 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.resourcemanager_v3.types.Organization: - The root node in the resource - hierarchy to which a particular entity's - (a company, for example) resources - belong. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = organizations.GetOrganizationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_organization, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_organizations(self, - request: Optional[Union[organizations.SearchOrganizationsRequest, dict]] = None, - *, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchOrganizationsAsyncPager: - r"""Searches organization resources that are visible to the user and - satisfy the specified filter. This method returns organizations - in an unspecified order. New organizations do not necessarily - appear at the end of the results, and may take a small amount of - time to appear. - - Search will only return organizations on which the user has the - permission ``resourcemanager.organizations.get`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_search_organizations(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchOrganizationsRequest( - ) - - # Make the request - page_result = client.search_organizations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]]): - The request object. The request sent to the ``SearchOrganizations`` method. - query (:class:`str`): - Optional. An optional query string used to filter the - Organizations to return in the response. Query rules are - case-insensitive. - - :: - - | Field | Description | - |------------------|--------------------------------------------| - | directoryCustomerId, owner.directoryCustomerId | Filters by directory - customer id. | - | domain | Filters by domain. | - - Organizations may be queried by ``directoryCustomerId`` - or by ``domain``, where the domain is a G Suite domain, - for example: - - - Query ``directorycustomerid:123456789`` returns - Organization resources with - ``owner.directory_customer_id`` equal to - ``123456789``. - - Query ``domain:google.com`` returns Organization - resources corresponding to the domain ``google.com``. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsAsyncPager: - The response returned from the SearchOrganizations - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([query]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = organizations.SearchOrganizationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_organizations, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.SearchOrganizationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for an organization resource. The - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the organization's resource name, - for example: "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.getIamPolicy`` on the specified - organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on an organization resource. - Replaces any existing policy. The ``resource`` field should be - the organization's resource name, for example: - "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.setIamPolicy`` on the specified - organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the specified - organization. The ``resource`` field should be the - organization's resource name, for example: "organizations/123". - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "OrganizationsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py deleted file mode 100644 index 75783a9..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/client.py +++ /dev/null @@ -1,1096 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.resourcemanager_v3.services.organizations import pagers -from google.cloud.resourcemanager_v3.types import organizations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OrganizationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import OrganizationsGrpcTransport -from .transports.grpc_asyncio import OrganizationsGrpcAsyncIOTransport -from .transports.rest import OrganizationsRestTransport - - -class OrganizationsClientMeta(type): - """Metaclass for the Organizations 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[OrganizationsTransport]] - _transport_registry["grpc"] = OrganizationsGrpcTransport - _transport_registry["grpc_asyncio"] = OrganizationsGrpcAsyncIOTransport - _transport_registry["rest"] = OrganizationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[OrganizationsTransport]: - """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 OrganizationsClient(metaclass=OrganizationsClientMeta): - """Allows users to manage their organization resources.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - OrganizationsClient: 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: - OrganizationsClient: 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) -> OrganizationsTransport: - """Returns the transport used by the client instance. - - Returns: - OrganizationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def organization_path(organization: str,) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_organization_path(path: str) -> Dict[str,str]: - """Parses a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OrganizationsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the organizations client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, OrganizationsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, OrganizationsTransport): - # transport is a OrganizationsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_organization(self, - request: Optional[Union[organizations.GetOrganizationRequest, 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]] = (), - ) -> organizations.Organization: - r"""Fetches an organization resource identified by the - specified resource name. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_get_organization(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetOrganizationRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]): - The request object. The request sent to the ``GetOrganization`` method. The - ``name`` field is required. ``organization_id`` is no - longer accepted. - name (str): - Required. The resource name of the Organization to - fetch. This is the organization's relative path in the - API, formatted as "organizations/[organizationId]". For - example, "organizations/1234". - - 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.resourcemanager_v3.types.Organization: - The root node in the resource - hierarchy to which a particular entity's - (a company, for example) resources - belong. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a organizations.GetOrganizationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, organizations.GetOrganizationRequest): - request = organizations.GetOrganizationRequest(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_organization] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_organizations(self, - request: Optional[Union[organizations.SearchOrganizationsRequest, dict]] = None, - *, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchOrganizationsPager: - r"""Searches organization resources that are visible to the user and - satisfy the specified filter. This method returns organizations - in an unspecified order. New organizations do not necessarily - appear at the end of the results, and may take a small amount of - time to appear. - - Search will only return organizations on which the user has the - permission ``resourcemanager.organizations.get`` - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_search_organizations(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchOrganizationsRequest( - ) - - # Make the request - page_result = client.search_organizations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]): - The request object. The request sent to the ``SearchOrganizations`` method. - query (str): - Optional. An optional query string used to filter the - Organizations to return in the response. Query rules are - case-insensitive. - - :: - - | Field | Description | - |------------------|--------------------------------------------| - | directoryCustomerId, owner.directoryCustomerId | Filters by directory - customer id. | - | domain | Filters by domain. | - - Organizations may be queried by ``directoryCustomerId`` - or by ``domain``, where the domain is a G Suite domain, - for example: - - - Query ``directorycustomerid:123456789`` returns - Organization resources with - ``owner.directory_customer_id`` equal to - ``123456789``. - - Query ``domain:google.com`` returns Organization - resources corresponding to the domain ``google.com``. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsPager: - The response returned from the SearchOrganizations - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([query]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a organizations.SearchOrganizationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, organizations.SearchOrganizationsRequest): - request = organizations.SearchOrganizationsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_organizations] - - # 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.SearchOrganizationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for an organization resource. The - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the organization's resource name, - for example: "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.getIamPolicy`` on the specified - organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on an organization resource. - Replaces any existing policy. The ``resource`` field should be - the organization's resource name, for example: - "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.setIamPolicy`` on the specified - organization. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns the permissions that a caller has on the specified - organization. The ``resource`` field should be the - organization's resource name, for example: "organizations/123". - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "OrganizationsClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "OrganizationsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py deleted file mode 100644 index 16ab297..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.resourcemanager_v3.types import organizations - - -class SearchOrganizationsPager: - """A pager for iterating through ``search_organizations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``organizations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchOrganizations`` requests and continue to iterate - through the ``organizations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` - 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[..., organizations.SearchOrganizationsResponse], - request: organizations.SearchOrganizationsRequest, - response: organizations.SearchOrganizationsResponse, - *, - 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.resourcemanager_v3.types.SearchOrganizationsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = organizations.SearchOrganizationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[organizations.SearchOrganizationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[organizations.Organization]: - for page in self.pages: - yield from page.organizations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchOrganizationsAsyncPager: - """A pager for iterating through ``search_organizations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``organizations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchOrganizations`` requests and continue to iterate - through the ``organizations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` - 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[organizations.SearchOrganizationsResponse]], - request: organizations.SearchOrganizationsRequest, - response: organizations.SearchOrganizationsResponse, - *, - 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.resourcemanager_v3.types.SearchOrganizationsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = organizations.SearchOrganizationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[organizations.SearchOrganizationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[organizations.Organization]: - async def async_generator(): - async for page in self.pages: - for response in page.organizations: - 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/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py deleted file mode 100644 index 01ddf02..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import OrganizationsTransport -from .grpc import OrganizationsGrpcTransport -from .grpc_asyncio import OrganizationsGrpcAsyncIOTransport -from .rest import OrganizationsRestTransport -from .rest import OrganizationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationsTransport]] -_transport_registry['grpc'] = OrganizationsGrpcTransport -_transport_registry['grpc_asyncio'] = OrganizationsGrpcAsyncIOTransport -_transport_registry['rest'] = OrganizationsRestTransport - -__all__ = ( - 'OrganizationsTransport', - 'OrganizationsGrpcTransport', - 'OrganizationsGrpcAsyncIOTransport', - 'OrganizationsRestTransport', - 'OrganizationsRestInterceptor', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py deleted file mode 100644 index d7c76b3..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/base.py +++ /dev/null @@ -1,219 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.resourcemanager_v3 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.resourcemanager_v3.types import organizations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class OrganizationsTransport(abc.ABC): - """Abstract transport class for Organizations.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_organization: gapic_v1.method.wrap_method( - self.get_organization, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.search_organizations: gapic_v1.method.wrap_method( - self.search_organizations, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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 get_organization(self) -> Callable[ - [organizations.GetOrganizationRequest], - Union[ - organizations.Organization, - Awaitable[organizations.Organization] - ]]: - raise NotImplementedError() - - @property - def search_organizations(self) -> Callable[ - [organizations.SearchOrganizationsRequest], - Union[ - organizations.SearchOrganizationsResponse, - Awaitable[organizations.SearchOrganizationsResponse] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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__ = ( - 'OrganizationsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py deleted file mode 100644 index 8797f8f..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc.py +++ /dev/null @@ -1,396 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.resourcemanager_v3.types import organizations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .base import OrganizationsTransport, DEFAULT_CLIENT_INFO - - -class OrganizationsGrpcTransport(OrganizationsTransport): - """gRPC backend transport for Organizations. - - Allows users to manage their organization resources. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudresourcemanager.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 get_organization(self) -> Callable[ - [organizations.GetOrganizationRequest], - organizations.Organization]: - r"""Return a callable for the get organization method over gRPC. - - Fetches an organization resource identified by the - specified resource name. - - Returns: - Callable[[~.GetOrganizationRequest], - ~.Organization]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization' not in self._stubs: - self._stubs['get_organization'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Organizations/GetOrganization', - request_serializer=organizations.GetOrganizationRequest.serialize, - response_deserializer=organizations.Organization.deserialize, - ) - return self._stubs['get_organization'] - - @property - def search_organizations(self) -> Callable[ - [organizations.SearchOrganizationsRequest], - organizations.SearchOrganizationsResponse]: - r"""Return a callable for the search organizations method over gRPC. - - Searches organization resources that are visible to the user and - satisfy the specified filter. This method returns organizations - in an unspecified order. New organizations do not necessarily - appear at the end of the results, and may take a small amount of - time to appear. - - Search will only return organizations on which the user has the - permission ``resourcemanager.organizations.get`` - - Returns: - Callable[[~.SearchOrganizationsRequest], - ~.SearchOrganizationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_organizations' not in self._stubs: - self._stubs['search_organizations'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations', - request_serializer=organizations.SearchOrganizationsRequest.serialize, - response_deserializer=organizations.SearchOrganizationsResponse.deserialize, - ) - return self._stubs['search_organizations'] - - @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 access control policy for an organization resource. The - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the organization's resource name, - for example: "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.getIamPolicy`` on the specified - organization. - - 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.cloud.resourcemanager.v3.Organizations/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on an organization resource. - Replaces any existing policy. The ``resource`` field should be - the organization's resource name, for example: - "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.setIamPolicy`` on the specified - organization. - - 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.cloud.resourcemanager.v3.Organizations/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the specified - organization. The ``resource`` field should be the - organization's resource name, for example: "organizations/123". - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.Organizations/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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'OrganizationsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py deleted file mode 100644 index 10aa4f0..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py +++ /dev/null @@ -1,395 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.resourcemanager_v3.types import organizations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .base import OrganizationsTransport, DEFAULT_CLIENT_INFO -from .grpc import OrganizationsGrpcTransport - - -class OrganizationsGrpcAsyncIOTransport(OrganizationsTransport): - """gRPC AsyncIO backend transport for Organizations. - - Allows users to manage their organization resources. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def get_organization(self) -> Callable[ - [organizations.GetOrganizationRequest], - Awaitable[organizations.Organization]]: - r"""Return a callable for the get organization method over gRPC. - - Fetches an organization resource identified by the - specified resource name. - - Returns: - Callable[[~.GetOrganizationRequest], - Awaitable[~.Organization]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_organization' not in self._stubs: - self._stubs['get_organization'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Organizations/GetOrganization', - request_serializer=organizations.GetOrganizationRequest.serialize, - response_deserializer=organizations.Organization.deserialize, - ) - return self._stubs['get_organization'] - - @property - def search_organizations(self) -> Callable[ - [organizations.SearchOrganizationsRequest], - Awaitable[organizations.SearchOrganizationsResponse]]: - r"""Return a callable for the search organizations method over gRPC. - - Searches organization resources that are visible to the user and - satisfy the specified filter. This method returns organizations - in an unspecified order. New organizations do not necessarily - appear at the end of the results, and may take a small amount of - time to appear. - - Search will only return organizations on which the user has the - permission ``resourcemanager.organizations.get`` - - Returns: - Callable[[~.SearchOrganizationsRequest], - Awaitable[~.SearchOrganizationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_organizations' not in self._stubs: - self._stubs['search_organizations'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations', - request_serializer=organizations.SearchOrganizationsRequest.serialize, - response_deserializer=organizations.SearchOrganizationsResponse.deserialize, - ) - return self._stubs['search_organizations'] - - @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 access control policy for an organization resource. The - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the organization's resource name, - for example: "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.getIamPolicy`` on the specified - organization. - - 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.cloud.resourcemanager.v3.Organizations/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on an organization resource. - Replaces any existing policy. The ``resource`` field should be - the organization's resource name, for example: - "organizations/123". - - Authorization requires the IAM permission - ``resourcemanager.organizations.setIamPolicy`` on the specified - organization. - - 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.cloud.resourcemanager.v3.Organizations/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the specified - organization. The ``resource`` field should be the - organization's resource name, for example: "organizations/123". - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.Organizations/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'OrganizationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py deleted file mode 100644 index 3acde45..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py +++ /dev/null @@ -1,907 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.resourcemanager_v3.types import organizations -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore - -from .base import OrganizationsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class OrganizationsRestInterceptor: - """Interceptor for Organizations. - - 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 OrganizationsRestTransport. - - .. code-block:: python - class MyCustomOrganizationsInterceptor(OrganizationsRestInterceptor): - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_organization(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_organization(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_organizations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_organizations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - transport = OrganizationsRestTransport(interceptor=MyCustomOrganizationsInterceptor()) - client = OrganizationsClient(transport=transport) - - - """ - 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 Organizations 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 Organizations server but before - it is returned to user code. - """ - return response - def pre_get_organization(self, request: organizations.GetOrganizationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[organizations.GetOrganizationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_organization - - Override in a subclass to manipulate the request or metadata - before they are sent to the Organizations server. - """ - return request, metadata - - def post_get_organization(self, response: organizations.Organization) -> organizations.Organization: - """Post-rpc interceptor for get_organization - - Override in a subclass to manipulate the response - after it is returned by the Organizations server but before - it is returned to user code. - """ - return response - def pre_search_organizations(self, request: organizations.SearchOrganizationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[organizations.SearchOrganizationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_organizations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Organizations server. - """ - return request, metadata - - def post_search_organizations(self, response: organizations.SearchOrganizationsResponse) -> organizations.SearchOrganizationsResponse: - """Post-rpc interceptor for search_organizations - - Override in a subclass to manipulate the response - after it is returned by the Organizations 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 Organizations 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 Organizations 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 Organizations 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 Organizations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class OrganizationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: OrganizationsRestInterceptor - - -class OrganizationsRestTransport(OrganizationsTransport): - """REST backend transport for Organizations. - - Allows users to manage their organization resources. - - 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 = 'cloudresourcemanager.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[OrganizationsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or OrganizationsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetIamPolicy(OrganizationsRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=organizations/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetOrganization(OrganizationsRestStub): - def __hash__(self): - return hash("GetOrganization") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: organizations.GetOrganizationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organizations.Organization: - r"""Call the get organization method over HTTP. - - Args: - request (~.organizations.GetOrganizationRequest): - The request object. The request sent to the ``GetOrganization`` method. The - ``name`` field is required. ``organization_id`` is no - longer accepted. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organizations.Organization: - The root node in the resource - hierarchy to which a particular entity's - (a company, for example) resources - belong. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/{name=organizations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_organization(request, metadata) - pb_request = organizations.GetOrganizationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organizations.Organization() - pb_resp = organizations.Organization.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization(resp) - return resp - - class _SearchOrganizations(OrganizationsRestStub): - def __hash__(self): - return hash("SearchOrganizations") - - def __call__(self, - request: organizations.SearchOrganizationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> organizations.SearchOrganizationsResponse: - r"""Call the search organizations method over HTTP. - - Args: - request (~.organizations.SearchOrganizationsRequest): - The request object. The request sent to the ``SearchOrganizations`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organizations.SearchOrganizationsResponse: - The response returned from the ``SearchOrganizations`` - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/organizations:search', - }, - ] - request, metadata = self._interceptor.pre_search_organizations(request, metadata) - pb_request = organizations.SearchOrganizationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = organizations.SearchOrganizationsResponse() - pb_resp = organizations.SearchOrganizationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_organizations(resp) - return resp - - class _SetIamPolicy(OrganizationsRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=organizations/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(OrganizationsRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=organizations/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_organization(self) -> Callable[ - [organizations.GetOrganizationRequest], - organizations.Organization]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetOrganization(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_organizations(self) -> Callable[ - [organizations.SearchOrganizationsRequest], - organizations.SearchOrganizationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchOrganizations(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'OrganizationsRestTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py deleted file mode 100644 index 7f60083..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ProjectsClient -from .async_client import ProjectsAsyncClient - -__all__ = ( - 'ProjectsClient', - 'ProjectsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py deleted file mode 100644 index a89cf72..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/async_client.py +++ /dev/null @@ -1,1779 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.projects import pagers -from google.cloud.resourcemanager_v3.types import projects -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ProjectsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProjectsGrpcAsyncIOTransport -from .client import ProjectsClient - - -class ProjectsAsyncClient: - """Manages Google Cloud Projects.""" - - _client: ProjectsClient - - DEFAULT_ENDPOINT = ProjectsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProjectsClient.DEFAULT_MTLS_ENDPOINT - - project_path = staticmethod(ProjectsClient.project_path) - parse_project_path = staticmethod(ProjectsClient.parse_project_path) - common_billing_account_path = staticmethod(ProjectsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProjectsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProjectsClient.common_folder_path) - parse_common_folder_path = staticmethod(ProjectsClient.parse_common_folder_path) - common_organization_path = staticmethod(ProjectsClient.common_organization_path) - parse_common_organization_path = staticmethod(ProjectsClient.parse_common_organization_path) - common_project_path = staticmethod(ProjectsClient.common_project_path) - parse_common_project_path = staticmethod(ProjectsClient.parse_common_project_path) - common_location_path = staticmethod(ProjectsClient.common_location_path) - parse_common_location_path = staticmethod(ProjectsClient.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: - ProjectsAsyncClient: The constructed client. - """ - return ProjectsClient.from_service_account_info.__func__(ProjectsAsyncClient, 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: - ProjectsAsyncClient: The constructed client. - """ - return ProjectsClient.from_service_account_file.__func__(ProjectsAsyncClient, 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 ProjectsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProjectsTransport: - """Returns the transport used by the client instance. - - Returns: - ProjectsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProjectsClient).get_transport_class, type(ProjectsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProjectsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the projects client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProjectsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProjectsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_project(self, - request: Optional[Union[projects.GetProjectRequest, 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]] = (), - ) -> projects.Project: - r"""Retrieves the project identified by the specified ``name`` (for - example, ``projects/415104041262``). - - The caller must have ``resourcemanager.projects.get`` permission - for this 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 resourcemanager_v3 - - async def sample_get_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetProjectRequest( - name="name_value", - ) - - # Make the request - response = await client.get_project(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.GetProjectRequest, dict]]): - The request object. The request sent to the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - name (:class:`str`): - Required. The name of the project (for example, - ``projects/415104041262``). - - 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.resourcemanager_v3.types.Project: - A project is a high-level Google - Cloud entity. It is a container for - ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.GetProjectRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_project, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_projects(self, - request: Optional[Union[projects.ListProjectsRequest, 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.ListProjectsAsyncPager: - r"""Lists projects that are direct children of the specified folder - or organization resource. ``list()`` provides a strongly - consistent view of the projects underneath the specified parent - resource. ``list()`` returns projects sorted based upon the - (ascending) lexical ordering of their ``display_name``. The - caller must have ``resourcemanager.projects.list`` permission on - the identified parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_list_projects(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListProjectsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_projects(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.ListProjectsRequest, dict]]): - The request object. The request sent to the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - parent (:class:`str`): - Required. The name of the parent - resource to list projects under. - For example, setting this field to - 'folders/1234' would list all projects - directly under that folder. - - 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.resourcemanager_v3.services.projects.pagers.ListProjectsAsyncPager: - A page of the response received from the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - - A paginated response where more pages are available - has next_page_token set. This token can be used in a - subsequent request to retrieve the next request page. - - NOTE: A response may contain fewer elements than the - request page_size and still have a next_page_token. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.ListProjectsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_projects, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListProjectsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_projects(self, - request: Optional[Union[projects.SearchProjectsRequest, dict]] = None, - *, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchProjectsAsyncPager: - r"""Search for projects that the caller has both - ``resourcemanager.projects.get`` permission on, and also satisfy - the specified query. - - This method returns projects in an unspecified order. - - This method is eventually consistent with project mutations; - this means that a newly created project may not appear in the - results or recent updates to an existing project may not be - reflected in the results. To retrieve the latest state of a - project, use the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_search_projects(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchProjectsRequest( - ) - - # Make the request - page_result = client.search_projects(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.SearchProjectsRequest, dict]]): - The request object. The request sent to the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - query (:class:`str`): - Optional. A query string for searching for projects that - the caller has ``resourcemanager.projects.get`` - permission to. If multiple fields are included in the - query, the it will return results that match any of the - fields. Some eligible fields are: - - :: - - | Field | Description | - |-------------------------|----------------------------------------------| - | displayName, name | Filters by displayName. | - | parent | Project's parent. (for example: folders/123, - organizations/*) Prefer parent field over parent.type and parent.id. | - | parent.type | Parent's type: `folder` or `organization`. | - | parent.id | Parent's id number (for example: 123) | - | id, projectId | Filters by projectId. | - | state, lifecycleState | Filters by state. | - | labels | Filters by label name or value. | - | labels. (where *key* is the name of a label) | Filters by label - name. | - - Search expressions are case insensitive. - - Some examples queries: - - :: - - | Query | Description | - |------------------|-----------------------------------------------------| - | name:how* | The project's name starts with "how". | - | name:Howl | The project's name is `Howl` or `howl`. | - | name:HOWL | Equivalent to above. | - | NAME:howl | Equivalent to above. | - | labels.color:* | The project has the label `color`. | - | labels.color:red | The project's label `color` has the value `red`. | - | labels.color:red labels.size:big | The project's label `color` has - the value `red` and its label `size` has the value `big`. | - - If no query is specified, the call will return projects - for which the user has the - ``resourcemanager.projects.get`` permission. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsAsyncPager: - A page of the response received from the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - - A paginated response where more pages are available - has next_page_token set. This token can be used in a - subsequent request to retrieve the next request page. - - 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([query]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.SearchProjectsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_projects, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.SearchProjectsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_project(self, - request: Optional[Union[projects.CreateProjectRequest, dict]] = None, - *, - project: Optional[projects.Project] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Request that a new project be created. The result is an - ``Operation`` which can be used to track the creation process. - This process usually takes a few seconds, but can sometimes take - much longer. The tracking ``Operation`` is automatically deleted - after a few hours, so there is no need to call - ``DeleteOperation``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_create_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateProjectRequest( - ) - - # Make the request - operation = client.create_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateProjectRequest, dict]]): - The request object. The request sent to the - [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] - method. - project (:class:`google.cloud.resourcemanager_v3.types.Project`): - Required. The Project to create. - - Project ID is required. If the requested ID is - unavailable, the request fails. - - If the ``parent`` field is set, the - ``resourcemanager.projects.create`` permission is - checked on the parent resource. If no parent is set and - the authorization credentials belong to an Organziation, - the parent will be set to that Organization. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.CreateProjectRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_project, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - projects.Project, - metadata_type=projects.CreateProjectMetadata, - ) - - # Done; return the response. - return response - - async def update_project(self, - request: Optional[Union[projects.UpdateProjectRequest, dict]] = None, - *, - project: Optional[projects.Project] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the ``display_name`` and labels of the project - identified by the specified ``name`` (for example, - ``projects/415104041262``). Deleting all labels requires an - update mask for labels field. - - The caller must have ``resourcemanager.projects.update`` - permission for this 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 resourcemanager_v3 - - async def sample_update_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UpdateProjectRequest( - ) - - # Make the request - operation = client.update_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateProjectRequest, dict]]): - The request object. The request sent to the - [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] - method. - - Only the ``display_name`` and ``labels`` fields can be - change. Use the - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method to change the ``parent`` field. - project (:class:`google.cloud.resourcemanager_v3.types.Project`): - Required. The new definition of the - project. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. An update mask to - selectively update fields. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.UpdateProjectRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_project, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project.name", request.project.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - projects.Project, - metadata_type=projects.UpdateProjectMetadata, - ) - - # Done; return the response. - return response - - async def move_project(self, - request: Optional[Union[projects.MoveProjectRequest, dict]] = None, - *, - name: Optional[str] = None, - destination_parent: 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"""Move a project to another place in your resource hierarchy, - under a new resource parent. - - Returns an operation which can be used to track the process of - the project move workflow. Upon success, the - ``Operation.response`` field will be populated with the moved - project. - - The caller must have ``resourcemanager.projects.update`` - permission on the project and have - ``resourcemanager.projects.move`` permission on the project's - current and proposed new parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_move_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveProjectRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.MoveProjectRequest, dict]]): - The request object. The request sent to - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method. - name (:class:`str`): - Required. The name of the project to - move. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - destination_parent (:class:`str`): - Required. The new parent to move the - Project under. - - This corresponds to the ``destination_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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick 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, destination_parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.MoveProjectRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if destination_parent is not None: - request.destination_parent = destination_parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.move_project, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - projects.Project, - metadata_type=projects.MoveProjectMetadata, - ) - - # Done; return the response. - return response - - async def delete_project(self, - request: Optional[Union[projects.DeleteProjectRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Marks the project identified by the specified ``name`` (for - example, ``projects/415104041262``) for deletion. - - This method will only affect the project if it has a lifecycle - state of - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. - - This method changes the Project's lifecycle state from - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] - to - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. - The deletion starts at an unspecified time, at which point the - Project is no longer accessible. - - Until the deletion completes, you can check the lifecycle state - checked by retrieving the project with [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], and the - project remains visible to [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects]. - However, you cannot update the project. - - After the deletion completes, the project is not retrievable by - the [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], - [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects], and - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - methods. - - This method behaves idempotently, such that deleting a - ``DELETE_REQUESTED`` project will not cause an error, but also - won't do anything. - - The caller must have ``resourcemanager.projects.delete`` - permissions for this 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 resourcemanager_v3 - - async def sample_delete_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteProjectRequest, dict]]): - The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] - method. - name (:class:`str`): - Required. The name of the Project (for example, - ``projects/415104041262``). - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.DeleteProjectRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_project, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - projects.Project, - metadata_type=projects.DeleteProjectMetadata, - ) - - # Done; return the response. - return response - - async def undelete_project(self, - request: Optional[Union[projects.UndeleteProjectRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Restores the project identified by the specified ``name`` (for - example, ``projects/415104041262``). You can only use this - method for a project that has a lifecycle state of - [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After - deletion starts, the project cannot be restored. - - The caller must have ``resourcemanager.projects.undelete`` - permission for this 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 resourcemanager_v3 - - async def sample_undelete_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]]): - The request object. The request sent to the [UndeleteProject] - [google.cloud.resourcemanager.v3.Projects.UndeleteProject] - method. - name (:class:`str`): - Required. The name of the project (for example, - ``projects/415104041262``). - - Required. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = projects.UndeleteProjectRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.undelete_project, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - projects.Project, - metadata_type=projects.UndeleteProjectMetadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Returns the IAM access control policy for the - specified project. Permission is denied if the policy or - the resource do not exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 for the specified project. - - CAUTION: This method will replace the existing policy, and - cannot be used to append additional IAM settings. - - Note: Removing service accounts from policies or changing their - roles can render services completely inoperable. It is important - to understand how the service account is being used before - removing or updating its roles. - - The following constraints apply when using ``setIamPolicy()``: - - - Project does not support ``allUsers`` and - ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of - a ``Policy``. - - - The owner role can be granted to a ``user``, - ``serviceAccount``, or a group that is part of an - organization. For example, group@myownpersonaldomain.com - could be added as an owner to a project in the - myownpersonaldomain.com organization, but not the - examplepetstore.com organization. - - - Service accounts can be made owners of a project directly - without any restrictions. However, to be added as an owner, a - user must be invited using the Cloud Platform console and - must accept the invitation. - - - A user cannot be granted the owner role using - ``setIamPolicy()``. The user must be granted the owner role - using the Cloud Platform Console and must explicitly accept - the invitation. - - - Invitations to grant the owner role cannot be sent using - ``setIamPolicy()``; they must be sent only using the Cloud - Platform Console. - - - Membership changes that leave the project without any owners - that have accepted the Terms of Service (ToS) will be - rejected. - - - If the project is not part of an organization, there must be - at least one owner who has accepted the Terms of Service - (ToS) agreement in the policy. Calling ``setIamPolicy()`` to - remove the last ToS-accepted owner from the policy will fail. - This restriction also applies to legacy projects that no - longer have owners who have accepted the ToS. Edits to IAM - policies will be rejected until the lack of a ToS-accepting - owner is rectified. - - - Calling this method requires enabling the App Engine Admin - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the - specified 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 resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ProjectsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py deleted file mode 100644 index 668cc88..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/client.py +++ /dev/null @@ -1,1964 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.projects import pagers -from google.cloud.resourcemanager_v3.types import projects -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ProjectsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProjectsGrpcTransport -from .transports.grpc_asyncio import ProjectsGrpcAsyncIOTransport -from .transports.rest import ProjectsRestTransport - - -class ProjectsClientMeta(type): - """Metaclass for the Projects 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[ProjectsTransport]] - _transport_registry["grpc"] = ProjectsGrpcTransport - _transport_registry["grpc_asyncio"] = ProjectsGrpcAsyncIOTransport - _transport_registry["rest"] = ProjectsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ProjectsTransport]: - """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 ProjectsClient(metaclass=ProjectsClientMeta): - """Manages Google Cloud Projects.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProjectsClient: 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: - ProjectsClient: 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) -> ProjectsTransport: - """Returns the transport used by the client instance. - - Returns: - ProjectsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def project_path(project: str,) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_project_path(path: str) -> Dict[str,str]: - """Parses a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProjectsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the projects client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProjectsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProjectsTransport): - # transport is a ProjectsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_project(self, - request: Optional[Union[projects.GetProjectRequest, 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]] = (), - ) -> projects.Project: - r"""Retrieves the project identified by the specified ``name`` (for - example, ``projects/415104041262``). - - The caller must have ``resourcemanager.projects.get`` permission - for this 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 resourcemanager_v3 - - def sample_get_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetProjectRequest( - name="name_value", - ) - - # Make the request - response = client.get_project(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.GetProjectRequest, dict]): - The request object. The request sent to the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - name (str): - Required. The name of the project (for example, - ``projects/415104041262``). - - 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.resourcemanager_v3.types.Project: - A project is a high-level Google - Cloud entity. It is a container for - ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.GetProjectRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.GetProjectRequest): - request = projects.GetProjectRequest(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_project] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_projects(self, - request: Optional[Union[projects.ListProjectsRequest, 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.ListProjectsPager: - r"""Lists projects that are direct children of the specified folder - or organization resource. ``list()`` provides a strongly - consistent view of the projects underneath the specified parent - resource. ``list()`` returns projects sorted based upon the - (ascending) lexical ordering of their ``display_name``. The - caller must have ``resourcemanager.projects.list`` permission on - the identified parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_list_projects(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListProjectsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_projects(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.ListProjectsRequest, dict]): - The request object. The request sent to the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - parent (str): - Required. The name of the parent - resource to list projects under. - For example, setting this field to - 'folders/1234' would list all projects - directly under that folder. - - 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.resourcemanager_v3.services.projects.pagers.ListProjectsPager: - A page of the response received from the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - - A paginated response where more pages are available - has next_page_token set. This token can be used in a - subsequent request to retrieve the next request page. - - NOTE: A response may contain fewer elements than the - request page_size and still have a next_page_token. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.ListProjectsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.ListProjectsRequest): - request = projects.ListProjectsRequest(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_projects] - - # 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.ListProjectsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_projects(self, - request: Optional[Union[projects.SearchProjectsRequest, dict]] = None, - *, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchProjectsPager: - r"""Search for projects that the caller has both - ``resourcemanager.projects.get`` permission on, and also satisfy - the specified query. - - This method returns projects in an unspecified order. - - This method is eventually consistent with project mutations; - this means that a newly created project may not appear in the - results or recent updates to an existing project may not be - reflected in the results. To retrieve the latest state of a - project, use the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_search_projects(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchProjectsRequest( - ) - - # Make the request - page_result = client.search_projects(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.SearchProjectsRequest, dict]): - The request object. The request sent to the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - query (str): - Optional. A query string for searching for projects that - the caller has ``resourcemanager.projects.get`` - permission to. If multiple fields are included in the - query, the it will return results that match any of the - fields. Some eligible fields are: - - :: - - | Field | Description | - |-------------------------|----------------------------------------------| - | displayName, name | Filters by displayName. | - | parent | Project's parent. (for example: folders/123, - organizations/*) Prefer parent field over parent.type and parent.id. | - | parent.type | Parent's type: `folder` or `organization`. | - | parent.id | Parent's id number (for example: 123) | - | id, projectId | Filters by projectId. | - | state, lifecycleState | Filters by state. | - | labels | Filters by label name or value. | - | labels. (where *key* is the name of a label) | Filters by label - name. | - - Search expressions are case insensitive. - - Some examples queries: - - :: - - | Query | Description | - |------------------|-----------------------------------------------------| - | name:how* | The project's name starts with "how". | - | name:Howl | The project's name is `Howl` or `howl`. | - | name:HOWL | Equivalent to above. | - | NAME:howl | Equivalent to above. | - | labels.color:* | The project has the label `color`. | - | labels.color:red | The project's label `color` has the value `red`. | - | labels.color:red labels.size:big | The project's label `color` has - the value `red` and its label `size` has the value `big`. | - - If no query is specified, the call will return projects - for which the user has the - ``resourcemanager.projects.get`` permission. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsPager: - A page of the response received from the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - - A paginated response where more pages are available - has next_page_token set. This token can be used in a - subsequent request to retrieve the next request page. - - 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([query]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.SearchProjectsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.SearchProjectsRequest): - request = projects.SearchProjectsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_projects] - - # 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.SearchProjectsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_project(self, - request: Optional[Union[projects.CreateProjectRequest, dict]] = None, - *, - project: Optional[projects.Project] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Request that a new project be created. The result is an - ``Operation`` which can be used to track the creation process. - This process usually takes a few seconds, but can sometimes take - much longer. The tracking ``Operation`` is automatically deleted - after a few hours, so there is no need to call - ``DeleteOperation``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_create_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateProjectRequest( - ) - - # Make the request - operation = client.create_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.CreateProjectRequest, dict]): - The request object. The request sent to the - [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] - method. - project (google.cloud.resourcemanager_v3.types.Project): - Required. The Project to create. - - Project ID is required. If the requested ID is - unavailable, the request fails. - - If the ``parent`` field is set, the - ``resourcemanager.projects.create`` permission is - checked on the parent resource. If no parent is set and - the authorization credentials belong to an Organziation, - the parent will be set to that Organization. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.CreateProjectRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.CreateProjectRequest): - request = projects.CreateProjectRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_project] - - # 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, - projects.Project, - metadata_type=projects.CreateProjectMetadata, - ) - - # Done; return the response. - return response - - def update_project(self, - request: Optional[Union[projects.UpdateProjectRequest, dict]] = None, - *, - project: Optional[projects.Project] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the ``display_name`` and labels of the project - identified by the specified ``name`` (for example, - ``projects/415104041262``). Deleting all labels requires an - update mask for labels field. - - The caller must have ``resourcemanager.projects.update`` - permission for this 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 resourcemanager_v3 - - def sample_update_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UpdateProjectRequest( - ) - - # Make the request - operation = client.update_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.UpdateProjectRequest, dict]): - The request object. The request sent to the - [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] - method. - - Only the ``display_name`` and ``labels`` fields can be - change. Use the - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method to change the ``parent`` field. - project (google.cloud.resourcemanager_v3.types.Project): - Required. The new definition of the - project. - - This corresponds to the ``project`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. An update mask to - selectively update fields. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([project, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.UpdateProjectRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.UpdateProjectRequest): - request = projects.UpdateProjectRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if project is not None: - request.project = project - 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_project] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("project.name", request.project.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - projects.Project, - metadata_type=projects.UpdateProjectMetadata, - ) - - # Done; return the response. - return response - - def move_project(self, - request: Optional[Union[projects.MoveProjectRequest, dict]] = None, - *, - name: Optional[str] = None, - destination_parent: 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"""Move a project to another place in your resource hierarchy, - under a new resource parent. - - Returns an operation which can be used to track the process of - the project move workflow. Upon success, the - ``Operation.response`` field will be populated with the moved - project. - - The caller must have ``resourcemanager.projects.update`` - permission on the project and have - ``resourcemanager.projects.move`` permission on the project's - current and proposed new parent. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_move_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveProjectRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.MoveProjectRequest, dict]): - The request object. The request sent to - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method. - name (str): - Required. The name of the project to - move. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - destination_parent (str): - Required. The new parent to move the - Project under. - - This corresponds to the ``destination_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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick 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, destination_parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.MoveProjectRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.MoveProjectRequest): - request = projects.MoveProjectRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if destination_parent is not None: - request.destination_parent = destination_parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.move_project] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - projects.Project, - metadata_type=projects.MoveProjectMetadata, - ) - - # Done; return the response. - return response - - def delete_project(self, - request: Optional[Union[projects.DeleteProjectRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Marks the project identified by the specified ``name`` (for - example, ``projects/415104041262``) for deletion. - - This method will only affect the project if it has a lifecycle - state of - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. - - This method changes the Project's lifecycle state from - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] - to - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. - The deletion starts at an unspecified time, at which point the - Project is no longer accessible. - - Until the deletion completes, you can check the lifecycle state - checked by retrieving the project with [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], and the - project remains visible to [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects]. - However, you cannot update the project. - - After the deletion completes, the project is not retrievable by - the [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], - [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects], and - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - methods. - - This method behaves idempotently, such that deleting a - ``DELETE_REQUESTED`` project will not cause an error, but also - won't do anything. - - The caller must have ``resourcemanager.projects.delete`` - permissions for this 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 resourcemanager_v3 - - def sample_delete_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.DeleteProjectRequest, dict]): - The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] - method. - name (str): - Required. The name of the Project (for example, - ``projects/415104041262``). - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.DeleteProjectRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.DeleteProjectRequest): - request = projects.DeleteProjectRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_project] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - projects.Project, - metadata_type=projects.DeleteProjectMetadata, - ) - - # Done; return the response. - return response - - def undelete_project(self, - request: Optional[Union[projects.UndeleteProjectRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Restores the project identified by the specified ``name`` (for - example, ``projects/415104041262``). You can only use this - method for a project that has a lifecycle state of - [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After - deletion starts, the project cannot be restored. - - The caller must have ``resourcemanager.projects.undelete`` - permission for this 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 resourcemanager_v3 - - def sample_undelete_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]): - The request object. The request sent to the [UndeleteProject] - [google.cloud.resourcemanager.v3.Projects.UndeleteProject] - method. - name (str): - Required. The name of the project (for example, - ``projects/415104041262``). - - Required. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a projects.UndeleteProjectRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, projects.UndeleteProjectRequest): - request = projects.UndeleteProjectRequest(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.undelete_project] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - projects.Project, - metadata_type=projects.UndeleteProjectMetadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Returns the IAM access control policy for the - specified project. Permission is denied if the policy or - the resource do not exist. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 for the specified project. - - CAUTION: This method will replace the existing policy, and - cannot be used to append additional IAM settings. - - Note: Removing service accounts from policies or changing their - roles can render services completely inoperable. It is important - to understand how the service account is being used before - removing or updating its roles. - - The following constraints apply when using ``setIamPolicy()``: - - - Project does not support ``allUsers`` and - ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of - a ``Policy``. - - - The owner role can be granted to a ``user``, - ``serviceAccount``, or a group that is part of an - organization. For example, group@myownpersonaldomain.com - could be added as an owner to a project in the - myownpersonaldomain.com organization, but not the - examplepetstore.com organization. - - - Service accounts can be made owners of a project directly - without any restrictions. However, to be added as an owner, a - user must be invited using the Cloud Platform console and - must accept the invitation. - - - A user cannot be granted the owner role using - ``setIamPolicy()``. The user must be granted the owner role - using the Cloud Platform Console and must explicitly accept - the invitation. - - - Invitations to grant the owner role cannot be sent using - ``setIamPolicy()``; they must be sent only using the Cloud - Platform Console. - - - Membership changes that leave the project without any owners - that have accepted the Terms of Service (ToS) will be - rejected. - - - If the project is not part of an organization, there must be - at least one owner who has accepted the Terms of Service - (ToS) agreement in the policy. Calling ``setIamPolicy()`` to - remove the last ToS-accepted owner from the policy will fail. - This restriction also applies to legacy projects that no - longer have owners who have accepted the ToS. Edits to IAM - policies will be rejected until the lack of a ToS-accepting - owner is rectified. - - - Calling this method requires enabling the App Engine Admin - API. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the - specified 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 resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ProjectsClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ProjectsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py deleted file mode 100644 index a0cae99..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/pagers.py +++ /dev/null @@ -1,260 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.resourcemanager_v3.types import projects - - -class ListProjectsPager: - """A pager for iterating through ``list_projects`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``projects`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListProjects`` requests and continue to iterate - through the ``projects`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` - 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[..., projects.ListProjectsResponse], - request: projects.ListProjectsRequest, - response: projects.ListProjectsResponse, - *, - 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.resourcemanager_v3.types.ListProjectsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListProjectsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = projects.ListProjectsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[projects.ListProjectsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[projects.Project]: - for page in self.pages: - yield from page.projects - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProjectsAsyncPager: - """A pager for iterating through ``list_projects`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``projects`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListProjects`` requests and continue to iterate - through the ``projects`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` - 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[projects.ListProjectsResponse]], - request: projects.ListProjectsRequest, - response: projects.ListProjectsResponse, - *, - 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.resourcemanager_v3.types.ListProjectsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListProjectsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = projects.ListProjectsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[projects.ListProjectsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[projects.Project]: - async def async_generator(): - async for page in self.pages: - for response in page.projects: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchProjectsPager: - """A pager for iterating through ``search_projects`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``projects`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchProjects`` requests and continue to iterate - through the ``projects`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` - 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[..., projects.SearchProjectsResponse], - request: projects.SearchProjectsRequest, - response: projects.SearchProjectsResponse, - *, - 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.resourcemanager_v3.types.SearchProjectsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.SearchProjectsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = projects.SearchProjectsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[projects.SearchProjectsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[projects.Project]: - for page in self.pages: - yield from page.projects - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchProjectsAsyncPager: - """A pager for iterating through ``search_projects`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``projects`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchProjects`` requests and continue to iterate - through the ``projects`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` - 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[projects.SearchProjectsResponse]], - request: projects.SearchProjectsRequest, - response: projects.SearchProjectsResponse, - *, - 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.resourcemanager_v3.types.SearchProjectsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.SearchProjectsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = projects.SearchProjectsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[projects.SearchProjectsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[projects.Project]: - async def async_generator(): - async for page in self.pages: - for response in page.projects: - 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/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py deleted file mode 100644 index 3cababc..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProjectsTransport -from .grpc import ProjectsGrpcTransport -from .grpc_asyncio import ProjectsGrpcAsyncIOTransport -from .rest import ProjectsRestTransport -from .rest import ProjectsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProjectsTransport]] -_transport_registry['grpc'] = ProjectsGrpcTransport -_transport_registry['grpc_asyncio'] = ProjectsGrpcAsyncIOTransport -_transport_registry['rest'] = ProjectsRestTransport - -__all__ = ( - 'ProjectsTransport', - 'ProjectsGrpcTransport', - 'ProjectsGrpcAsyncIOTransport', - 'ProjectsRestTransport', - 'ProjectsRestInterceptor', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py deleted file mode 100644 index 52b9140..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/base.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.resourcemanager_v3 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.resourcemanager_v3.types import projects -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 ProjectsTransport(abc.ABC): - """Abstract transport class for Projects.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_project: gapic_v1.method.wrap_method( - self.get_project, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_projects: gapic_v1.method.wrap_method( - self.list_projects, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.search_projects: gapic_v1.method.wrap_method( - self.search_projects, - default_timeout=60.0, - client_info=client_info, - ), - self.create_project: gapic_v1.method.wrap_method( - self.create_project, - default_timeout=60.0, - client_info=client_info, - ), - self.update_project: gapic_v1.method.wrap_method( - self.update_project, - default_timeout=60.0, - client_info=client_info, - ), - self.move_project: gapic_v1.method.wrap_method( - self.move_project, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_project: gapic_v1.method.wrap_method( - self.delete_project, - default_timeout=60.0, - client_info=client_info, - ), - self.undelete_project: gapic_v1.method.wrap_method( - self.undelete_project, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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 get_project(self) -> Callable[ - [projects.GetProjectRequest], - Union[ - projects.Project, - Awaitable[projects.Project] - ]]: - raise NotImplementedError() - - @property - def list_projects(self) -> Callable[ - [projects.ListProjectsRequest], - Union[ - projects.ListProjectsResponse, - Awaitable[projects.ListProjectsResponse] - ]]: - raise NotImplementedError() - - @property - def search_projects(self) -> Callable[ - [projects.SearchProjectsRequest], - Union[ - projects.SearchProjectsResponse, - Awaitable[projects.SearchProjectsResponse] - ]]: - raise NotImplementedError() - - @property - def create_project(self) -> Callable[ - [projects.CreateProjectRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_project(self) -> Callable[ - [projects.UpdateProjectRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def move_project(self) -> Callable[ - [projects.MoveProjectRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_project(self) -> Callable[ - [projects.DeleteProjectRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undelete_project(self) -> Callable[ - [projects.UndeleteProjectRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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__ = ( - 'ProjectsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py deleted file mode 100644 index c963001..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc.py +++ /dev/null @@ -1,684 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.resourcemanager_v3.types import projects -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 ProjectsTransport, DEFAULT_CLIENT_INFO - - -class ProjectsGrpcTransport(ProjectsTransport): - """gRPC backend transport for Projects. - - Manages Google Cloud Projects. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudresourcemanager.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 get_project(self) -> Callable[ - [projects.GetProjectRequest], - projects.Project]: - r"""Return a callable for the get project method over gRPC. - - Retrieves the project identified by the specified ``name`` (for - example, ``projects/415104041262``). - - The caller must have ``resourcemanager.projects.get`` permission - for this project. - - Returns: - Callable[[~.GetProjectRequest], - ~.Project]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_project' not in self._stubs: - self._stubs['get_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/GetProject', - request_serializer=projects.GetProjectRequest.serialize, - response_deserializer=projects.Project.deserialize, - ) - return self._stubs['get_project'] - - @property - def list_projects(self) -> Callable[ - [projects.ListProjectsRequest], - projects.ListProjectsResponse]: - r"""Return a callable for the list projects method over gRPC. - - Lists projects that are direct children of the specified folder - or organization resource. ``list()`` provides a strongly - consistent view of the projects underneath the specified parent - resource. ``list()`` returns projects sorted based upon the - (ascending) lexical ordering of their ``display_name``. The - caller must have ``resourcemanager.projects.list`` permission on - the identified parent. - - Returns: - Callable[[~.ListProjectsRequest], - ~.ListProjectsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_projects' not in self._stubs: - self._stubs['list_projects'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/ListProjects', - request_serializer=projects.ListProjectsRequest.serialize, - response_deserializer=projects.ListProjectsResponse.deserialize, - ) - return self._stubs['list_projects'] - - @property - def search_projects(self) -> Callable[ - [projects.SearchProjectsRequest], - projects.SearchProjectsResponse]: - r"""Return a callable for the search projects method over gRPC. - - Search for projects that the caller has both - ``resourcemanager.projects.get`` permission on, and also satisfy - the specified query. - - This method returns projects in an unspecified order. - - This method is eventually consistent with project mutations; - this means that a newly created project may not appear in the - results or recent updates to an existing project may not be - reflected in the results. To retrieve the latest state of a - project, use the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - - Returns: - Callable[[~.SearchProjectsRequest], - ~.SearchProjectsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_projects' not in self._stubs: - self._stubs['search_projects'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/SearchProjects', - request_serializer=projects.SearchProjectsRequest.serialize, - response_deserializer=projects.SearchProjectsResponse.deserialize, - ) - return self._stubs['search_projects'] - - @property - def create_project(self) -> Callable[ - [projects.CreateProjectRequest], - operations_pb2.Operation]: - r"""Return a callable for the create project method over gRPC. - - Request that a new project be created. The result is an - ``Operation`` which can be used to track the creation process. - This process usually takes a few seconds, but can sometimes take - much longer. The tracking ``Operation`` is automatically deleted - after a few hours, so there is no need to call - ``DeleteOperation``. - - Returns: - Callable[[~.CreateProjectRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_project' not in self._stubs: - self._stubs['create_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/CreateProject', - request_serializer=projects.CreateProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_project'] - - @property - def update_project(self) -> Callable[ - [projects.UpdateProjectRequest], - operations_pb2.Operation]: - r"""Return a callable for the update project method over gRPC. - - Updates the ``display_name`` and labels of the project - identified by the specified ``name`` (for example, - ``projects/415104041262``). Deleting all labels requires an - update mask for labels field. - - The caller must have ``resourcemanager.projects.update`` - permission for this project. - - Returns: - Callable[[~.UpdateProjectRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_project' not in self._stubs: - self._stubs['update_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/UpdateProject', - request_serializer=projects.UpdateProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_project'] - - @property - def move_project(self) -> Callable[ - [projects.MoveProjectRequest], - operations_pb2.Operation]: - r"""Return a callable for the move project method over gRPC. - - Move a project to another place in your resource hierarchy, - under a new resource parent. - - Returns an operation which can be used to track the process of - the project move workflow. Upon success, the - ``Operation.response`` field will be populated with the moved - project. - - The caller must have ``resourcemanager.projects.update`` - permission on the project and have - ``resourcemanager.projects.move`` permission on the project's - current and proposed new parent. - - Returns: - Callable[[~.MoveProjectRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'move_project' not in self._stubs: - self._stubs['move_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/MoveProject', - request_serializer=projects.MoveProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['move_project'] - - @property - def delete_project(self) -> Callable[ - [projects.DeleteProjectRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete project method over gRPC. - - Marks the project identified by the specified ``name`` (for - example, ``projects/415104041262``) for deletion. - - This method will only affect the project if it has a lifecycle - state of - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. - - This method changes the Project's lifecycle state from - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] - to - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. - The deletion starts at an unspecified time, at which point the - Project is no longer accessible. - - Until the deletion completes, you can check the lifecycle state - checked by retrieving the project with [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], and the - project remains visible to [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects]. - However, you cannot update the project. - - After the deletion completes, the project is not retrievable by - the [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], - [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects], and - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - methods. - - This method behaves idempotently, such that deleting a - ``DELETE_REQUESTED`` project will not cause an error, but also - won't do anything. - - The caller must have ``resourcemanager.projects.delete`` - permissions for this project. - - Returns: - Callable[[~.DeleteProjectRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_project' not in self._stubs: - self._stubs['delete_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/DeleteProject', - request_serializer=projects.DeleteProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_project'] - - @property - def undelete_project(self) -> Callable[ - [projects.UndeleteProjectRequest], - operations_pb2.Operation]: - r"""Return a callable for the undelete project method over gRPC. - - Restores the project identified by the specified ``name`` (for - example, ``projects/415104041262``). You can only use this - method for a project that has a lifecycle state of - [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After - deletion starts, the project cannot be restored. - - The caller must have ``resourcemanager.projects.undelete`` - permission for this project. - - Returns: - Callable[[~.UndeleteProjectRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'undelete_project' not in self._stubs: - self._stubs['undelete_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/UndeleteProject', - request_serializer=projects.UndeleteProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undelete_project'] - - @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. - - Returns the IAM access control policy for the - specified project. Permission is denied if the policy or - the resource do not exist. - - 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.cloud.resourcemanager.v3.Projects/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 for the specified project. - - CAUTION: This method will replace the existing policy, and - cannot be used to append additional IAM settings. - - Note: Removing service accounts from policies or changing their - roles can render services completely inoperable. It is important - to understand how the service account is being used before - removing or updating its roles. - - The following constraints apply when using ``setIamPolicy()``: - - - Project does not support ``allUsers`` and - ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of - a ``Policy``. - - - The owner role can be granted to a ``user``, - ``serviceAccount``, or a group that is part of an - organization. For example, group@myownpersonaldomain.com - could be added as an owner to a project in the - myownpersonaldomain.com organization, but not the - examplepetstore.com organization. - - - Service accounts can be made owners of a project directly - without any restrictions. However, to be added as an owner, a - user must be invited using the Cloud Platform console and - must accept the invitation. - - - A user cannot be granted the owner role using - ``setIamPolicy()``. The user must be granted the owner role - using the Cloud Platform Console and must explicitly accept - the invitation. - - - Invitations to grant the owner role cannot be sent using - ``setIamPolicy()``; they must be sent only using the Cloud - Platform Console. - - - Membership changes that leave the project without any owners - that have accepted the Terms of Service (ToS) will be - rejected. - - - If the project is not part of an organization, there must be - at least one owner who has accepted the Terms of Service - (ToS) agreement in the policy. Calling ``setIamPolicy()`` to - remove the last ToS-accepted owner from the policy will fail. - This restriction also applies to legacy projects that no - longer have owners who have accepted the ToS. Edits to IAM - policies will be rejected until the lack of a ToS-accepting - owner is rectified. - - - Calling this method requires enabling the App Engine Admin - API. - - 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.cloud.resourcemanager.v3.Projects/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the - specified project. - - 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.cloud.resourcemanager.v3.Projects/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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProjectsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py deleted file mode 100644 index 127c24c..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py +++ /dev/null @@ -1,683 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.resourcemanager_v3.types import projects -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 ProjectsTransport, DEFAULT_CLIENT_INFO -from .grpc import ProjectsGrpcTransport - - -class ProjectsGrpcAsyncIOTransport(ProjectsTransport): - """gRPC AsyncIO backend transport for Projects. - - Manages Google Cloud Projects. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_project(self) -> Callable[ - [projects.GetProjectRequest], - Awaitable[projects.Project]]: - r"""Return a callable for the get project method over gRPC. - - Retrieves the project identified by the specified ``name`` (for - example, ``projects/415104041262``). - - The caller must have ``resourcemanager.projects.get`` permission - for this project. - - Returns: - Callable[[~.GetProjectRequest], - Awaitable[~.Project]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_project' not in self._stubs: - self._stubs['get_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/GetProject', - request_serializer=projects.GetProjectRequest.serialize, - response_deserializer=projects.Project.deserialize, - ) - return self._stubs['get_project'] - - @property - def list_projects(self) -> Callable[ - [projects.ListProjectsRequest], - Awaitable[projects.ListProjectsResponse]]: - r"""Return a callable for the list projects method over gRPC. - - Lists projects that are direct children of the specified folder - or organization resource. ``list()`` provides a strongly - consistent view of the projects underneath the specified parent - resource. ``list()`` returns projects sorted based upon the - (ascending) lexical ordering of their ``display_name``. The - caller must have ``resourcemanager.projects.list`` permission on - the identified parent. - - Returns: - Callable[[~.ListProjectsRequest], - Awaitable[~.ListProjectsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_projects' not in self._stubs: - self._stubs['list_projects'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/ListProjects', - request_serializer=projects.ListProjectsRequest.serialize, - response_deserializer=projects.ListProjectsResponse.deserialize, - ) - return self._stubs['list_projects'] - - @property - def search_projects(self) -> Callable[ - [projects.SearchProjectsRequest], - Awaitable[projects.SearchProjectsResponse]]: - r"""Return a callable for the search projects method over gRPC. - - Search for projects that the caller has both - ``resourcemanager.projects.get`` permission on, and also satisfy - the specified query. - - This method returns projects in an unspecified order. - - This method is eventually consistent with project mutations; - this means that a newly created project may not appear in the - results or recent updates to an existing project may not be - reflected in the results. To retrieve the latest state of a - project, use the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - - Returns: - Callable[[~.SearchProjectsRequest], - Awaitable[~.SearchProjectsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_projects' not in self._stubs: - self._stubs['search_projects'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/SearchProjects', - request_serializer=projects.SearchProjectsRequest.serialize, - response_deserializer=projects.SearchProjectsResponse.deserialize, - ) - return self._stubs['search_projects'] - - @property - def create_project(self) -> Callable[ - [projects.CreateProjectRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create project method over gRPC. - - Request that a new project be created. The result is an - ``Operation`` which can be used to track the creation process. - This process usually takes a few seconds, but can sometimes take - much longer. The tracking ``Operation`` is automatically deleted - after a few hours, so there is no need to call - ``DeleteOperation``. - - Returns: - Callable[[~.CreateProjectRequest], - 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_project' not in self._stubs: - self._stubs['create_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/CreateProject', - request_serializer=projects.CreateProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_project'] - - @property - def update_project(self) -> Callable[ - [projects.UpdateProjectRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update project method over gRPC. - - Updates the ``display_name`` and labels of the project - identified by the specified ``name`` (for example, - ``projects/415104041262``). Deleting all labels requires an - update mask for labels field. - - The caller must have ``resourcemanager.projects.update`` - permission for this project. - - Returns: - Callable[[~.UpdateProjectRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_project' not in self._stubs: - self._stubs['update_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/UpdateProject', - request_serializer=projects.UpdateProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_project'] - - @property - def move_project(self) -> Callable[ - [projects.MoveProjectRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the move project method over gRPC. - - Move a project to another place in your resource hierarchy, - under a new resource parent. - - Returns an operation which can be used to track the process of - the project move workflow. Upon success, the - ``Operation.response`` field will be populated with the moved - project. - - The caller must have ``resourcemanager.projects.update`` - permission on the project and have - ``resourcemanager.projects.move`` permission on the project's - current and proposed new parent. - - Returns: - Callable[[~.MoveProjectRequest], - 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 'move_project' not in self._stubs: - self._stubs['move_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/MoveProject', - request_serializer=projects.MoveProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['move_project'] - - @property - def delete_project(self) -> Callable[ - [projects.DeleteProjectRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete project method over gRPC. - - Marks the project identified by the specified ``name`` (for - example, ``projects/415104041262``) for deletion. - - This method will only affect the project if it has a lifecycle - state of - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]. - - This method changes the Project's lifecycle state from - [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE] - to - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED]. - The deletion starts at an unspecified time, at which point the - Project is no longer accessible. - - Until the deletion completes, you can check the lifecycle state - checked by retrieving the project with [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], and the - project remains visible to [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects]. - However, you cannot update the project. - - After the deletion completes, the project is not retrievable by - the [GetProject] - [google.cloud.resourcemanager.v3.Projects.GetProject], - [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects], and - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - methods. - - This method behaves idempotently, such that deleting a - ``DELETE_REQUESTED`` project will not cause an error, but also - won't do anything. - - The caller must have ``resourcemanager.projects.delete`` - permissions for this project. - - Returns: - Callable[[~.DeleteProjectRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_project' not in self._stubs: - self._stubs['delete_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/DeleteProject', - request_serializer=projects.DeleteProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_project'] - - @property - def undelete_project(self) -> Callable[ - [projects.UndeleteProjectRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undelete project method over gRPC. - - Restores the project identified by the specified ``name`` (for - example, ``projects/415104041262``). You can only use this - method for a project that has a lifecycle state of - [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After - deletion starts, the project cannot be restored. - - The caller must have ``resourcemanager.projects.undelete`` - permission for this project. - - Returns: - Callable[[~.UndeleteProjectRequest], - 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 'undelete_project' not in self._stubs: - self._stubs['undelete_project'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.Projects/UndeleteProject', - request_serializer=projects.UndeleteProjectRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undelete_project'] - - @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. - - Returns the IAM access control policy for the - specified project. Permission is denied if the policy or - the resource do not exist. - - 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.cloud.resourcemanager.v3.Projects/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 for the specified project. - - CAUTION: This method will replace the existing policy, and - cannot be used to append additional IAM settings. - - Note: Removing service accounts from policies or changing their - roles can render services completely inoperable. It is important - to understand how the service account is being used before - removing or updating its roles. - - The following constraints apply when using ``setIamPolicy()``: - - - Project does not support ``allUsers`` and - ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of - a ``Policy``. - - - The owner role can be granted to a ``user``, - ``serviceAccount``, or a group that is part of an - organization. For example, group@myownpersonaldomain.com - could be added as an owner to a project in the - myownpersonaldomain.com organization, but not the - examplepetstore.com organization. - - - Service accounts can be made owners of a project directly - without any restrictions. However, to be added as an owner, a - user must be invited using the Cloud Platform console and - must accept the invitation. - - - A user cannot be granted the owner role using - ``setIamPolicy()``. The user must be granted the owner role - using the Cloud Platform Console and must explicitly accept - the invitation. - - - Invitations to grant the owner role cannot be sent using - ``setIamPolicy()``; they must be sent only using the Cloud - Platform Console. - - - Membership changes that leave the project without any owners - that have accepted the Terms of Service (ToS) will be - rejected. - - - If the project is not part of an organization, there must be - at least one owner who has accepted the Terms of Service - (ToS) agreement in the policy. Calling ``setIamPolicy()`` to - remove the last ToS-accepted owner from the policy will fail. - This restriction also applies to legacy projects that no - longer have owners who have accepted the ToS. Edits to IAM - policies will be rejected until the lack of a ToS-accepting - owner is rectified. - - - Calling this method requires enabling the App Engine Admin - API. - - 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.cloud.resourcemanager.v3.Projects/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the - specified project. - - 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.cloud.resourcemanager.v3.Projects/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'ProjectsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py deleted file mode 100644 index ee5e055..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/projects/transports/rest.py +++ /dev/null @@ -1,1676 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.resourcemanager_v3.types import projects -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 ProjectsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ProjectsRestInterceptor: - """Interceptor for Projects. - - 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 ProjectsRestTransport. - - .. code-block:: python - class MyCustomProjectsInterceptor(ProjectsRestInterceptor): - def pre_create_project(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_project(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_project(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_project(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_project(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_project(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_projects(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_projects(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_move_project(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_move_project(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_projects(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_projects(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undelete_project(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undelete_project(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_project(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_project(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ProjectsRestTransport(interceptor=MyCustomProjectsInterceptor()) - client = ProjectsClient(transport=transport) - - - """ - def pre_create_project(self, request: projects.CreateProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.CreateProjectRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_project - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_create_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_project - - Override in a subclass to manipulate the response - after it is returned by the Projects server but before - it is returned to user code. - """ - return response - def pre_delete_project(self, request: projects.DeleteProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.DeleteProjectRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_project - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_delete_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_project - - Override in a subclass to manipulate the response - after it is returned by the Projects 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 Projects 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 Projects server but before - it is returned to user code. - """ - return response - def pre_get_project(self, request: projects.GetProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.GetProjectRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_project - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_get_project(self, response: projects.Project) -> projects.Project: - """Post-rpc interceptor for get_project - - Override in a subclass to manipulate the response - after it is returned by the Projects server but before - it is returned to user code. - """ - return response - def pre_list_projects(self, request: projects.ListProjectsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.ListProjectsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_projects - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_list_projects(self, response: projects.ListProjectsResponse) -> projects.ListProjectsResponse: - """Post-rpc interceptor for list_projects - - Override in a subclass to manipulate the response - after it is returned by the Projects server but before - it is returned to user code. - """ - return response - def pre_move_project(self, request: projects.MoveProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.MoveProjectRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for move_project - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_move_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for move_project - - Override in a subclass to manipulate the response - after it is returned by the Projects server but before - it is returned to user code. - """ - return response - def pre_search_projects(self, request: projects.SearchProjectsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.SearchProjectsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_projects - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_search_projects(self, response: projects.SearchProjectsResponse) -> projects.SearchProjectsResponse: - """Post-rpc interceptor for search_projects - - Override in a subclass to manipulate the response - after it is returned by the Projects 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 Projects 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 Projects 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 Projects 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 Projects server but before - it is returned to user code. - """ - return response - def pre_undelete_project(self, request: projects.UndeleteProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.UndeleteProjectRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for undelete_project - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_undelete_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undelete_project - - Override in a subclass to manipulate the response - after it is returned by the Projects server but before - it is returned to user code. - """ - return response - def pre_update_project(self, request: projects.UpdateProjectRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[projects.UpdateProjectRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_project - - Override in a subclass to manipulate the request or metadata - before they are sent to the Projects server. - """ - return request, metadata - - def post_update_project(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_project - - Override in a subclass to manipulate the response - after it is returned by the Projects server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ProjectsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ProjectsRestInterceptor - - -class ProjectsRestTransport(ProjectsTransport): - """REST backend transport for Projects. - - Manages Google Cloud Projects. - - 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 = 'cloudresourcemanager.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[ProjectsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ProjectsRestInterceptor() - 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': '/v3/{name=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="v3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateProject(ProjectsRestStub): - def __hash__(self): - return hash("CreateProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.CreateProjectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create project method over HTTP. - - Args: - request (~.projects.CreateProjectRequest): - The request object. The request sent to the - [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/projects', - 'body': 'project', - }, - ] - request, metadata = self._interceptor.pre_create_project(request, metadata) - pb_request = projects.CreateProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_project(resp) - return resp - - class _DeleteProject(ProjectsRestStub): - def __hash__(self): - return hash("DeleteProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.DeleteProjectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete project method over HTTP. - - Args: - request (~.projects.DeleteProjectRequest): - The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v3/{name=projects/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_project(request, metadata) - pb_request = projects.DeleteProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_project(resp) - return resp - - class _GetIamPolicy(ProjectsRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=projects/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetProject(ProjectsRestStub): - def __hash__(self): - return hash("GetProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.GetProjectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> projects.Project: - r"""Call the get project method over HTTP. - - Args: - request (~.projects.GetProjectRequest): - The request object. The request sent to the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.projects.Project: - A project is a high-level Google - Cloud entity. It is a container for - ACLs, APIs, App Engine Apps, VMs, and - other Google Cloud Platform resources. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/{name=projects/*}', - }, - ] - request, metadata = self._interceptor.pre_get_project(request, metadata) - pb_request = projects.GetProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = projects.Project() - pb_resp = projects.Project.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_project(resp) - return resp - - class _ListProjects(ProjectsRestStub): - def __hash__(self): - return hash("ListProjects") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.ListProjectsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> projects.ListProjectsResponse: - r"""Call the list projects method over HTTP. - - Args: - request (~.projects.ListProjectsRequest): - The request object. The request sent to the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.projects.ListProjectsResponse: - A page of the response received from the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - - A paginated response where more pages are available has - ``next_page_token`` set. This token can be used in a - subsequent request to retrieve the next request page. - - NOTE: A response may contain fewer elements than the - request ``page_size`` and still have a - ``next_page_token``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/projects', - }, - ] - request, metadata = self._interceptor.pre_list_projects(request, metadata) - pb_request = projects.ListProjectsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = projects.ListProjectsResponse() - pb_resp = projects.ListProjectsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_projects(resp) - return resp - - class _MoveProject(ProjectsRestStub): - def __hash__(self): - return hash("MoveProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.MoveProjectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the move project method over HTTP. - - Args: - request (~.projects.MoveProjectRequest): - The request object. The request sent to - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{name=projects/*}:move', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_move_project(request, metadata) - pb_request = projects.MoveProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_move_project(resp) - return resp - - class _SearchProjects(ProjectsRestStub): - def __hash__(self): - return hash("SearchProjects") - - def __call__(self, - request: projects.SearchProjectsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> projects.SearchProjectsResponse: - r"""Call the search projects method over HTTP. - - Args: - request (~.projects.SearchProjectsRequest): - The request object. The request sent to the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.projects.SearchProjectsResponse: - A page of the response received from the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - - A paginated response where more pages are available has - ``next_page_token`` set. This token can be used in a - subsequent request to retrieve the next request page. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/projects:search', - }, - ] - request, metadata = self._interceptor.pre_search_projects(request, metadata) - pb_request = projects.SearchProjectsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = projects.SearchProjectsResponse() - pb_resp = projects.SearchProjectsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_projects(resp) - return resp - - class _SetIamPolicy(ProjectsRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=projects/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(ProjectsRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=projects/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UndeleteProject(ProjectsRestStub): - def __hash__(self): - return hash("UndeleteProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.UndeleteProjectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the undelete project method over HTTP. - - Args: - request (~.projects.UndeleteProjectRequest): - The request object. The request sent to the [UndeleteProject] - [google.cloud.resourcemanager.v3.Projects.UndeleteProject] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{name=projects/*}:undelete', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_undelete_project(request, metadata) - pb_request = projects.UndeleteProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_undelete_project(resp) - return resp - - class _UpdateProject(ProjectsRestStub): - def __hash__(self): - return hash("UpdateProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: projects.UpdateProjectRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update project method over HTTP. - - Args: - request (~.projects.UpdateProjectRequest): - The request object. The request sent to the - [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] - method. - - Only the ``display_name`` and ``labels`` fields can be - change. Use the - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method to change the ``parent`` field. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v3/{project.name=projects/*}', - 'body': 'project', - }, - ] - request, metadata = self._interceptor.pre_update_project(request, metadata) - pb_request = projects.UpdateProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_project(resp) - return resp - - @property - def create_project(self) -> Callable[ - [projects.CreateProjectRequest], - 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._CreateProject(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_project(self) -> Callable[ - [projects.DeleteProjectRequest], - 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._DeleteProject(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_project(self) -> Callable[ - [projects.GetProjectRequest], - projects.Project]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetProject(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_projects(self) -> Callable[ - [projects.ListProjectsRequest], - projects.ListProjectsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListProjects(self._session, self._host, self._interceptor) # type: ignore - - @property - def move_project(self) -> Callable[ - [projects.MoveProjectRequest], - 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._MoveProject(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_projects(self) -> Callable[ - [projects.SearchProjectsRequest], - projects.SearchProjectsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SearchProjects(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def undelete_project(self) -> Callable[ - [projects.UndeleteProjectRequest], - 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._UndeleteProject(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_project(self) -> Callable[ - [projects.UpdateProjectRequest], - 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._UpdateProject(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ProjectsRestTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py deleted file mode 100644 index 6c815d1..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import TagBindingsClient -from .async_client import TagBindingsAsyncClient - -__all__ = ( - 'TagBindingsClient', - 'TagBindingsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py deleted file mode 100644 index ba25499..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py +++ /dev/null @@ -1,556 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.tag_bindings import pagers -from google.cloud.resourcemanager_v3.types import tag_bindings -from google.protobuf import empty_pb2 # type: ignore -from .transports.base import TagBindingsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TagBindingsGrpcAsyncIOTransport -from .client import TagBindingsClient - - -class TagBindingsAsyncClient: - """Allow users to create and manage TagBindings between - TagValues and different cloud resources throughout the GCP - resource hierarchy. - """ - - _client: TagBindingsClient - - DEFAULT_ENDPOINT = TagBindingsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TagBindingsClient.DEFAULT_MTLS_ENDPOINT - - tag_binding_path = staticmethod(TagBindingsClient.tag_binding_path) - parse_tag_binding_path = staticmethod(TagBindingsClient.parse_tag_binding_path) - common_billing_account_path = staticmethod(TagBindingsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TagBindingsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TagBindingsClient.common_folder_path) - parse_common_folder_path = staticmethod(TagBindingsClient.parse_common_folder_path) - common_organization_path = staticmethod(TagBindingsClient.common_organization_path) - parse_common_organization_path = staticmethod(TagBindingsClient.parse_common_organization_path) - common_project_path = staticmethod(TagBindingsClient.common_project_path) - parse_common_project_path = staticmethod(TagBindingsClient.parse_common_project_path) - common_location_path = staticmethod(TagBindingsClient.common_location_path) - parse_common_location_path = staticmethod(TagBindingsClient.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: - TagBindingsAsyncClient: The constructed client. - """ - return TagBindingsClient.from_service_account_info.__func__(TagBindingsAsyncClient, 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: - TagBindingsAsyncClient: The constructed client. - """ - return TagBindingsClient.from_service_account_file.__func__(TagBindingsAsyncClient, 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 TagBindingsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TagBindingsTransport: - """Returns the transport used by the client instance. - - Returns: - TagBindingsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TagBindingsClient).get_transport_class, type(TagBindingsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, TagBindingsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the tag bindings client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.TagBindingsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = TagBindingsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_tag_bindings(self, - request: Optional[Union[tag_bindings.ListTagBindingsRequest, 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.ListTagBindingsAsyncPager: - r"""Lists the TagBindings for the given cloud resource, as specified - with ``parent``. - - NOTE: The ``parent`` field is expected to be a full resource - name: - https://cloud.google.com/apis/design/resource_names#full_resource_name - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_list_tag_bindings(): - # Create a client - client = resourcemanager_v3.TagBindingsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_bindings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagBindingsRequest, dict]]): - The request object. The request message to list all - TagBindings for a parent. - parent (:class:`str`): - Required. The full resource name of a - resource for which you want to list - existing TagBindings. E.g. - "//cloudresourcemanager.googleapis.com/projects/123" - - 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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsAsyncPager: - The ListTagBindings response. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_bindings.ListTagBindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_tag_bindings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListTagBindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_tag_binding(self, - request: Optional[Union[tag_bindings.CreateTagBindingRequest, dict]] = None, - *, - tag_binding: Optional[tag_bindings.TagBinding] = 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 TagBinding between a TagValue and a cloud - resource (currently project, folder, or organization). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_create_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateTagBindingRequest( - ) - - # Make the request - operation = client.create_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagBindingRequest, dict]]): - The request object. The request message to create a - TagBinding. - tag_binding (:class:`google.cloud.resourcemanager_v3.types.TagBinding`): - Required. The TagBinding to be - created. - - This corresponds to the ``tag_binding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.TagBinding` A TagBinding represents a connection between a TagValue and a cloud - resource (currently project, folder, or - organization). Once a TagBinding is created, the - TagValue is applied to all the descendants of the - cloud resource. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_binding]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_bindings.CreateTagBindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_binding is not None: - request.tag_binding = tag_binding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_tag_binding, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - tag_bindings.TagBinding, - metadata_type=tag_bindings.CreateTagBindingMetadata, - ) - - # Done; return the response. - return response - - async def delete_tag_binding(self, - request: Optional[Union[tag_bindings.DeleteTagBindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a TagBinding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_delete_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest, dict]]): - The request object. The request message to delete a - TagBinding. - name (:class:`str`): - Required. The name of the TagBinding. This is a String - of the form: ``tagBindings/{id}`` (e.g. - ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_bindings.DeleteTagBindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_tag_binding, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=tag_bindings.DeleteTagBindingMetadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "TagBindingsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py deleted file mode 100644 index 662246a..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/client.py +++ /dev/null @@ -1,754 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.tag_bindings import pagers -from google.cloud.resourcemanager_v3.types import tag_bindings -from google.protobuf import empty_pb2 # type: ignore -from .transports.base import TagBindingsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TagBindingsGrpcTransport -from .transports.grpc_asyncio import TagBindingsGrpcAsyncIOTransport -from .transports.rest import TagBindingsRestTransport - - -class TagBindingsClientMeta(type): - """Metaclass for the TagBindings 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[TagBindingsTransport]] - _transport_registry["grpc"] = TagBindingsGrpcTransport - _transport_registry["grpc_asyncio"] = TagBindingsGrpcAsyncIOTransport - _transport_registry["rest"] = TagBindingsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TagBindingsTransport]: - """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 TagBindingsClient(metaclass=TagBindingsClientMeta): - """Allow users to create and manage TagBindings between - TagValues and different cloud resources throughout the GCP - resource hierarchy. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TagBindingsClient: 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: - TagBindingsClient: 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) -> TagBindingsTransport: - """Returns the transport used by the client instance. - - Returns: - TagBindingsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def tag_binding_path(tag_binding: str,) -> str: - """Returns a fully-qualified tag_binding string.""" - return "tagBindings/{tag_binding}".format(tag_binding=tag_binding, ) - - @staticmethod - def parse_tag_binding_path(path: str) -> Dict[str,str]: - """Parses a tag_binding path into its component segments.""" - m = re.match(r"^tagBindings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TagBindingsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the tag bindings client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, TagBindingsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, TagBindingsTransport): - # transport is a TagBindingsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_tag_bindings(self, - request: Optional[Union[tag_bindings.ListTagBindingsRequest, 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.ListTagBindingsPager: - r"""Lists the TagBindings for the given cloud resource, as specified - with ``parent``. - - NOTE: The ``parent`` field is expected to be a full resource - name: - https://cloud.google.com/apis/design/resource_names#full_resource_name - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_list_tag_bindings(): - # Create a client - client = resourcemanager_v3.TagBindingsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_bindings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.ListTagBindingsRequest, dict]): - The request object. The request message to list all - TagBindings for a parent. - parent (str): - Required. The full resource name of a - resource for which you want to list - existing TagBindings. E.g. - "//cloudresourcemanager.googleapis.com/projects/123" - - 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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsPager: - The ListTagBindings response. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_bindings.ListTagBindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_bindings.ListTagBindingsRequest): - request = tag_bindings.ListTagBindingsRequest(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_tag_bindings] - - # 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.ListTagBindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_tag_binding(self, - request: Optional[Union[tag_bindings.CreateTagBindingRequest, dict]] = None, - *, - tag_binding: Optional[tag_bindings.TagBinding] = 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 TagBinding between a TagValue and a cloud - resource (currently project, folder, or organization). - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_create_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateTagBindingRequest( - ) - - # Make the request - operation = client.create_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.CreateTagBindingRequest, dict]): - The request object. The request message to create a - TagBinding. - tag_binding (google.cloud.resourcemanager_v3.types.TagBinding): - Required. The TagBinding to be - created. - - This corresponds to the ``tag_binding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.TagBinding` A TagBinding represents a connection between a TagValue and a cloud - resource (currently project, folder, or - organization). Once a TagBinding is created, the - TagValue is applied to all the descendants of the - cloud resource. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_binding]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_bindings.CreateTagBindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_bindings.CreateTagBindingRequest): - request = tag_bindings.CreateTagBindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_binding is not None: - request.tag_binding = tag_binding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_binding] - - # 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, - tag_bindings.TagBinding, - metadata_type=tag_bindings.CreateTagBindingMetadata, - ) - - # Done; return the response. - return response - - def delete_tag_binding(self, - request: Optional[Union[tag_bindings.DeleteTagBindingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a TagBinding. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_delete_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest, dict]): - The request object. The request message to delete a - TagBinding. - name (str): - Required. The name of the TagBinding. This is a String - of the form: ``tagBindings/{id}`` (e.g. - ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_bindings.DeleteTagBindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_bindings.DeleteTagBindingRequest): - request = tag_bindings.DeleteTagBindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_binding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=tag_bindings.DeleteTagBindingMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "TagBindingsClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "TagBindingsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py deleted file mode 100644 index 427ffc2..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.resourcemanager_v3.types import tag_bindings - - -class ListTagBindingsPager: - """A pager for iterating through ``list_tag_bindings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tag_bindings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTagBindings`` requests and continue to iterate - through the ``tag_bindings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` - 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[..., tag_bindings.ListTagBindingsResponse], - request: tag_bindings.ListTagBindingsRequest, - response: tag_bindings.ListTagBindingsResponse, - *, - 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.resourcemanager_v3.types.ListTagBindingsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListTagBindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tag_bindings.ListTagBindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[tag_bindings.ListTagBindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tag_bindings.TagBinding]: - for page in self.pages: - yield from page.tag_bindings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagBindingsAsyncPager: - """A pager for iterating through ``list_tag_bindings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tag_bindings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTagBindings`` requests and continue to iterate - through the ``tag_bindings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` - 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[tag_bindings.ListTagBindingsResponse]], - request: tag_bindings.ListTagBindingsRequest, - response: tag_bindings.ListTagBindingsResponse, - *, - 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.resourcemanager_v3.types.ListTagBindingsRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListTagBindingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tag_bindings.ListTagBindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[tag_bindings.ListTagBindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[tag_bindings.TagBinding]: - async def async_generator(): - async for page in self.pages: - for response in page.tag_bindings: - 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/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py deleted file mode 100644 index 94fccb4..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import TagBindingsTransport -from .grpc import TagBindingsGrpcTransport -from .grpc_asyncio import TagBindingsGrpcAsyncIOTransport -from .rest import TagBindingsRestTransport -from .rest import TagBindingsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TagBindingsTransport]] -_transport_registry['grpc'] = TagBindingsGrpcTransport -_transport_registry['grpc_asyncio'] = TagBindingsGrpcAsyncIOTransport -_transport_registry['rest'] = TagBindingsRestTransport - -__all__ = ( - 'TagBindingsTransport', - 'TagBindingsGrpcTransport', - 'TagBindingsGrpcAsyncIOTransport', - 'TagBindingsRestTransport', - 'TagBindingsRestInterceptor', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py deleted file mode 100644 index e1cdac1..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py +++ /dev/null @@ -1,190 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.resourcemanager_v3 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.resourcemanager_v3.types import tag_bindings -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class TagBindingsTransport(abc.ABC): - """Abstract transport class for TagBindings.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_tag_bindings: gapic_v1.method.wrap_method( - self.list_tag_bindings, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_tag_binding: gapic_v1.method.wrap_method( - self.create_tag_binding, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_tag_binding: gapic_v1.method.wrap_method( - self.delete_tag_binding, - default_timeout=60.0, - 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 list_tag_bindings(self) -> Callable[ - [tag_bindings.ListTagBindingsRequest], - Union[ - tag_bindings.ListTagBindingsResponse, - Awaitable[tag_bindings.ListTagBindingsResponse] - ]]: - raise NotImplementedError() - - @property - def create_tag_binding(self) -> Callable[ - [tag_bindings.CreateTagBindingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_tag_binding(self) -> Callable[ - [tag_bindings.DeleteTagBindingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'TagBindingsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py deleted file mode 100644 index f183ccf..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc.py +++ /dev/null @@ -1,343 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_bindings -from google.longrunning import operations_pb2 # type: ignore -from .base import TagBindingsTransport, DEFAULT_CLIENT_INFO - - -class TagBindingsGrpcTransport(TagBindingsTransport): - """gRPC backend transport for TagBindings. - - Allow users to create and manage TagBindings between - TagValues and different cloud resources throughout the GCP - resource hierarchy. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudresourcemanager.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 list_tag_bindings(self) -> Callable[ - [tag_bindings.ListTagBindingsRequest], - tag_bindings.ListTagBindingsResponse]: - r"""Return a callable for the list tag bindings method over gRPC. - - Lists the TagBindings for the given cloud resource, as specified - with ``parent``. - - NOTE: The ``parent`` field is expected to be a full resource - name: - https://cloud.google.com/apis/design/resource_names#full_resource_name - - Returns: - Callable[[~.ListTagBindingsRequest], - ~.ListTagBindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_bindings' not in self._stubs: - self._stubs['list_tag_bindings'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagBindings/ListTagBindings', - request_serializer=tag_bindings.ListTagBindingsRequest.serialize, - response_deserializer=tag_bindings.ListTagBindingsResponse.deserialize, - ) - return self._stubs['list_tag_bindings'] - - @property - def create_tag_binding(self) -> Callable[ - [tag_bindings.CreateTagBindingRequest], - operations_pb2.Operation]: - r"""Return a callable for the create tag binding method over gRPC. - - Creates a TagBinding between a TagValue and a cloud - resource (currently project, folder, or organization). - - Returns: - Callable[[~.CreateTagBindingRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_binding' not in self._stubs: - self._stubs['create_tag_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagBindings/CreateTagBinding', - request_serializer=tag_bindings.CreateTagBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tag_binding'] - - @property - def delete_tag_binding(self) -> Callable[ - [tag_bindings.DeleteTagBindingRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete tag binding method over gRPC. - - Deletes a TagBinding. - - Returns: - Callable[[~.DeleteTagBindingRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_tag_binding' not in self._stubs: - self._stubs['delete_tag_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagBindings/DeleteTagBinding', - request_serializer=tag_bindings.DeleteTagBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tag_binding'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TagBindingsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py deleted file mode 100644 index 2de3983..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py +++ /dev/null @@ -1,342 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_bindings -from google.longrunning import operations_pb2 # type: ignore -from .base import TagBindingsTransport, DEFAULT_CLIENT_INFO -from .grpc import TagBindingsGrpcTransport - - -class TagBindingsGrpcAsyncIOTransport(TagBindingsTransport): - """gRPC AsyncIO backend transport for TagBindings. - - Allow users to create and manage TagBindings between - TagValues and different cloud resources throughout the GCP - resource hierarchy. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_tag_bindings(self) -> Callable[ - [tag_bindings.ListTagBindingsRequest], - Awaitable[tag_bindings.ListTagBindingsResponse]]: - r"""Return a callable for the list tag bindings method over gRPC. - - Lists the TagBindings for the given cloud resource, as specified - with ``parent``. - - NOTE: The ``parent`` field is expected to be a full resource - name: - https://cloud.google.com/apis/design/resource_names#full_resource_name - - Returns: - Callable[[~.ListTagBindingsRequest], - Awaitable[~.ListTagBindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_bindings' not in self._stubs: - self._stubs['list_tag_bindings'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagBindings/ListTagBindings', - request_serializer=tag_bindings.ListTagBindingsRequest.serialize, - response_deserializer=tag_bindings.ListTagBindingsResponse.deserialize, - ) - return self._stubs['list_tag_bindings'] - - @property - def create_tag_binding(self) -> Callable[ - [tag_bindings.CreateTagBindingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create tag binding method over gRPC. - - Creates a TagBinding between a TagValue and a cloud - resource (currently project, folder, or organization). - - Returns: - Callable[[~.CreateTagBindingRequest], - 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_tag_binding' not in self._stubs: - self._stubs['create_tag_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagBindings/CreateTagBinding', - request_serializer=tag_bindings.CreateTagBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tag_binding'] - - @property - def delete_tag_binding(self) -> Callable[ - [tag_bindings.DeleteTagBindingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete tag binding method over gRPC. - - Deletes a TagBinding. - - Returns: - Callable[[~.DeleteTagBindingRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_tag_binding' not in self._stubs: - self._stubs['delete_tag_binding'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagBindings/DeleteTagBinding', - request_serializer=tag_bindings.DeleteTagBindingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tag_binding'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'TagBindingsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py deleted file mode 100644 index 2d36c96..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py +++ /dev/null @@ -1,558 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.resourcemanager_v3.types import tag_bindings -from google.longrunning import operations_pb2 # type: ignore - -from .base import TagBindingsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class TagBindingsRestInterceptor: - """Interceptor for TagBindings. - - 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 TagBindingsRestTransport. - - .. code-block:: python - class MyCustomTagBindingsInterceptor(TagBindingsRestInterceptor): - def pre_create_tag_binding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_tag_binding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_tag_binding(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_tag_binding(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tag_bindings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tag_bindings(self, response): - logging.log(f"Received response: {response}") - return response - - transport = TagBindingsRestTransport(interceptor=MyCustomTagBindingsInterceptor()) - client = TagBindingsClient(transport=transport) - - - """ - def pre_create_tag_binding(self, request: tag_bindings.CreateTagBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_bindings.CreateTagBindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_tag_binding - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagBindings server. - """ - return request, metadata - - def post_create_tag_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_tag_binding - - Override in a subclass to manipulate the response - after it is returned by the TagBindings server but before - it is returned to user code. - """ - return response - def pre_delete_tag_binding(self, request: tag_bindings.DeleteTagBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_bindings.DeleteTagBindingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_tag_binding - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagBindings server. - """ - return request, metadata - - def post_delete_tag_binding(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_tag_binding - - Override in a subclass to manipulate the response - after it is returned by the TagBindings server but before - it is returned to user code. - """ - return response - def pre_list_tag_bindings(self, request: tag_bindings.ListTagBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_bindings.ListTagBindingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tag_bindings - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagBindings server. - """ - return request, metadata - - def post_list_tag_bindings(self, response: tag_bindings.ListTagBindingsResponse) -> tag_bindings.ListTagBindingsResponse: - """Post-rpc interceptor for list_tag_bindings - - Override in a subclass to manipulate the response - after it is returned by the TagBindings server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class TagBindingsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: TagBindingsRestInterceptor - - -class TagBindingsRestTransport(TagBindingsTransport): - """REST backend transport for TagBindings. - - Allow users to create and manage TagBindings between - TagValues and different cloud resources throughout the GCP - resource hierarchy. - - 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 = 'cloudresourcemanager.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[TagBindingsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or TagBindingsRestInterceptor() - 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': '/v3/{name=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="v3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateTagBinding(TagBindingsRestStub): - def __hash__(self): - return hash("CreateTagBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_bindings.CreateTagBindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create tag binding method over HTTP. - - Args: - request (~.tag_bindings.CreateTagBindingRequest): - The request object. The request message to create a - TagBinding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/tagBindings', - 'body': 'tag_binding', - }, - ] - request, metadata = self._interceptor.pre_create_tag_binding(request, metadata) - pb_request = tag_bindings.CreateTagBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_tag_binding(resp) - return resp - - class _DeleteTagBinding(TagBindingsRestStub): - def __hash__(self): - return hash("DeleteTagBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_bindings.DeleteTagBindingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete tag binding method over HTTP. - - Args: - request (~.tag_bindings.DeleteTagBindingRequest): - The request object. The request message to delete a - TagBinding. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v3/{name=tagBindings/**}', - }, - ] - request, metadata = self._interceptor.pre_delete_tag_binding(request, metadata) - pb_request = tag_bindings.DeleteTagBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_tag_binding(resp) - return resp - - class _ListTagBindings(TagBindingsRestStub): - def __hash__(self): - return hash("ListTagBindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_bindings.ListTagBindingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tag_bindings.ListTagBindingsResponse: - r"""Call the list tag bindings method over HTTP. - - Args: - request (~.tag_bindings.ListTagBindingsRequest): - The request object. The request message to list all - TagBindings for a parent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tag_bindings.ListTagBindingsResponse: - The ListTagBindings response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/tagBindings', - }, - ] - request, metadata = self._interceptor.pre_list_tag_bindings(request, metadata) - pb_request = tag_bindings.ListTagBindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tag_bindings.ListTagBindingsResponse() - pb_resp = tag_bindings.ListTagBindingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tag_bindings(resp) - return resp - - @property - def create_tag_binding(self) -> Callable[ - [tag_bindings.CreateTagBindingRequest], - 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._CreateTagBinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_tag_binding(self) -> Callable[ - [tag_bindings.DeleteTagBindingRequest], - 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._DeleteTagBinding(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tag_bindings(self) -> Callable[ - [tag_bindings.ListTagBindingsRequest], - tag_bindings.ListTagBindingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListTagBindings(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'TagBindingsRestTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py deleted file mode 100644 index e42d5be..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import TagKeysClient -from .async_client import TagKeysAsyncClient - -__all__ = ( - 'TagKeysClient', - 'TagKeysAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py deleted file mode 100644 index b4029ec..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py +++ /dev/null @@ -1,1249 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.tag_keys import pagers -from google.cloud.resourcemanager_v3.types import tag_keys -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TagKeysTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TagKeysGrpcAsyncIOTransport -from .client import TagKeysClient - - -class TagKeysAsyncClient: - """Allow users to create and manage tag keys.""" - - _client: TagKeysClient - - DEFAULT_ENDPOINT = TagKeysClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TagKeysClient.DEFAULT_MTLS_ENDPOINT - - tag_key_path = staticmethod(TagKeysClient.tag_key_path) - parse_tag_key_path = staticmethod(TagKeysClient.parse_tag_key_path) - common_billing_account_path = staticmethod(TagKeysClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TagKeysClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TagKeysClient.common_folder_path) - parse_common_folder_path = staticmethod(TagKeysClient.parse_common_folder_path) - common_organization_path = staticmethod(TagKeysClient.common_organization_path) - parse_common_organization_path = staticmethod(TagKeysClient.parse_common_organization_path) - common_project_path = staticmethod(TagKeysClient.common_project_path) - parse_common_project_path = staticmethod(TagKeysClient.parse_common_project_path) - common_location_path = staticmethod(TagKeysClient.common_location_path) - parse_common_location_path = staticmethod(TagKeysClient.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: - TagKeysAsyncClient: The constructed client. - """ - return TagKeysClient.from_service_account_info.__func__(TagKeysAsyncClient, 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: - TagKeysAsyncClient: The constructed client. - """ - return TagKeysClient.from_service_account_file.__func__(TagKeysAsyncClient, 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 TagKeysClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TagKeysTransport: - """Returns the transport used by the client instance. - - Returns: - TagKeysTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TagKeysClient).get_transport_class, type(TagKeysClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, TagKeysTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the tag keys client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.TagKeysTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = TagKeysClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_tag_keys(self, - request: Optional[Union[tag_keys.ListTagKeysRequest, 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.ListTagKeysAsyncPager: - r"""Lists all TagKeys for a parent resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_list_tag_keys(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_keys(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagKeysRequest, dict]]): - The request object. The request message for listing all - TagKeys under a parent resource. - parent (:class:`str`): - Required. The resource name of the new TagKey's parent. - Must be of the form ``folders/{folder_id}`` or - ``organizations/{org_id}``. - - 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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysAsyncPager: - The ListTagKeys response message. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_keys.ListTagKeysRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_tag_keys, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListTagKeysAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_tag_key(self, - request: Optional[Union[tag_keys.GetTagKeyRequest, 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]] = (), - ) -> tag_keys.TagKey: - r"""Retrieves a TagKey. This method will return - ``PERMISSION_DENIED`` if the key does not exist or the user does - not have permission to view it. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_get_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagKeyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tag_key(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.GetTagKeyRequest, dict]]): - The request object. The request message for getting a - TagKey. - name (:class:`str`): - Required. A resource name in the format - ``tagKeys/{id}``, such as ``tagKeys/123``. - - 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.resourcemanager_v3.types.TagKey: - A TagKey, used to group a set of - TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_keys.GetTagKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_tag_key, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_tag_key(self, - request: Optional[Union[tag_keys.CreateTagKeyRequest, dict]] = None, - *, - tag_key: Optional[tag_keys.TagKey] = 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 TagKey. If another request with the - same parameters is sent while the original request is in - process, the second request will receive an error. A - maximum of 300 TagKeys can exist under a parent at any - given time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_create_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.create_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagKeyRequest, dict]]): - The request object. The request message for creating a - TagKey. - tag_key (:class:`google.cloud.resourcemanager_v3.types.TagKey`): - Required. The TagKey to be created. Only fields - ``short_name``, ``description``, and ``parent`` are - considered during the creation request. - - This corresponds to the ``tag_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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.resourcemanager_v3.types.TagKey` A - TagKey, used to group a set of TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_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.") - - request = tag_keys.CreateTagKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_key is not None: - request.tag_key = tag_key - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_tag_key, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - tag_keys.TagKey, - metadata_type=tag_keys.CreateTagKeyMetadata, - ) - - # Done; return the response. - return response - - async def update_tag_key(self, - request: Optional[Union[tag_keys.UpdateTagKeyRequest, dict]] = None, - *, - tag_key: Optional[tag_keys.TagKey] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the attributes of the TagKey resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_update_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.update_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest, dict]]): - The request object. The request message for updating a - TagKey. - tag_key (:class:`google.cloud.resourcemanager_v3.types.TagKey`): - Required. The new definition of the TagKey. Only the - ``description`` and ``etag`` fields can be updated by - this request. If the ``etag`` field is not empty, it - must match the ``etag`` field of the existing tag key. - Otherwise, ``FAILED_PRECONDITION`` will be returned. - - This corresponds to the ``tag_key`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Fields to be updated. The mask may only contain - ``description`` or ``etag``. If omitted entirely, both - ``description`` and ``etag`` are assumed to be - significant. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.resourcemanager_v3.types.TagKey` A - TagKey, used to group a set of TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_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.") - - request = tag_keys.UpdateTagKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_key is not None: - request.tag_key = tag_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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_tag_key, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_key.name", request.tag_key.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - tag_keys.TagKey, - metadata_type=tag_keys.UpdateTagKeyMetadata, - ) - - # Done; return the response. - return response - - async def delete_tag_key(self, - request: Optional[Union[tag_keys.DeleteTagKeyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a TagKey. The TagKey cannot be deleted if it - has any child TagValues. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_delete_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagKeyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest, dict]]): - The request object. The request message for deleting a - TagKey. - name (:class:`str`): - Required. The resource name of a TagKey to be deleted in - the format ``tagKeys/123``. The TagKey cannot be a - parent of any existing TagValues or it will not be - deleted successfully. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.resourcemanager_v3.types.TagKey` A - TagKey, used to group a set of TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_keys.DeleteTagKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_tag_key, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - tag_keys.TagKey, - metadata_type=tag_keys.DeleteTagKeyMetadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for a TagKey. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". The caller must have - ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` - permission on the specified TagKey. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on a TagKey, replacing any - existing policy. The ``resource`` field should be the TagKey's - resource name. For example, "tagKeys/1234". The caller must have - ``resourcemanager.tagKeys.setIamPolicy`` permission on the - identified tagValue. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagKey. - The ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "TagKeysAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py deleted file mode 100644 index 7c8e97d..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/client.py +++ /dev/null @@ -1,1434 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.tag_keys import pagers -from google.cloud.resourcemanager_v3.types import tag_keys -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TagKeysTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TagKeysGrpcTransport -from .transports.grpc_asyncio import TagKeysGrpcAsyncIOTransport -from .transports.rest import TagKeysRestTransport - - -class TagKeysClientMeta(type): - """Metaclass for the TagKeys 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[TagKeysTransport]] - _transport_registry["grpc"] = TagKeysGrpcTransport - _transport_registry["grpc_asyncio"] = TagKeysGrpcAsyncIOTransport - _transport_registry["rest"] = TagKeysRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TagKeysTransport]: - """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 TagKeysClient(metaclass=TagKeysClientMeta): - """Allow users to create and manage tag keys.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TagKeysClient: 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: - TagKeysClient: 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) -> TagKeysTransport: - """Returns the transport used by the client instance. - - Returns: - TagKeysTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def tag_key_path(tag_key: str,) -> str: - """Returns a fully-qualified tag_key string.""" - return "tagKeys/{tag_key}".format(tag_key=tag_key, ) - - @staticmethod - def parse_tag_key_path(path: str) -> Dict[str,str]: - """Parses a tag_key path into its component segments.""" - m = re.match(r"^tagKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TagKeysTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the tag keys client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, TagKeysTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, TagKeysTransport): - # transport is a TagKeysTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_tag_keys(self, - request: Optional[Union[tag_keys.ListTagKeysRequest, 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.ListTagKeysPager: - r"""Lists all TagKeys for a parent resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_list_tag_keys(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_keys(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.ListTagKeysRequest, dict]): - The request object. The request message for listing all - TagKeys under a parent resource. - parent (str): - Required. The resource name of the new TagKey's parent. - Must be of the form ``folders/{folder_id}`` or - ``organizations/{org_id}``. - - 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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysPager: - The ListTagKeys response message. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_keys.ListTagKeysRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_keys.ListTagKeysRequest): - request = tag_keys.ListTagKeysRequest(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_tag_keys] - - # 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.ListTagKeysPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_tag_key(self, - request: Optional[Union[tag_keys.GetTagKeyRequest, 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]] = (), - ) -> tag_keys.TagKey: - r"""Retrieves a TagKey. This method will return - ``PERMISSION_DENIED`` if the key does not exist or the user does - not have permission to view it. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_get_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagKeyRequest( - name="name_value", - ) - - # Make the request - response = client.get_tag_key(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.GetTagKeyRequest, dict]): - The request object. The request message for getting a - TagKey. - name (str): - Required. A resource name in the format - ``tagKeys/{id}``, such as ``tagKeys/123``. - - 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.resourcemanager_v3.types.TagKey: - A TagKey, used to group a set of - TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_keys.GetTagKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_keys.GetTagKeyRequest): - request = tag_keys.GetTagKeyRequest(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_tag_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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_tag_key(self, - request: Optional[Union[tag_keys.CreateTagKeyRequest, dict]] = None, - *, - tag_key: Optional[tag_keys.TagKey] = 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 TagKey. If another request with the - same parameters is sent while the original request is in - process, the second request will receive an error. A - maximum of 300 TagKeys can exist under a parent at any - given time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_create_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.create_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.CreateTagKeyRequest, dict]): - The request object. The request message for creating a - TagKey. - tag_key (google.cloud.resourcemanager_v3.types.TagKey): - Required. The TagKey to be created. Only fields - ``short_name``, ``description``, and ``parent`` are - considered during the creation request. - - This corresponds to the ``tag_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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.resourcemanager_v3.types.TagKey` A - TagKey, used to group a set of TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_keys.CreateTagKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_keys.CreateTagKeyRequest): - request = tag_keys.CreateTagKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_key is not None: - request.tag_key = tag_key - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_key] - - # 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, - tag_keys.TagKey, - metadata_type=tag_keys.CreateTagKeyMetadata, - ) - - # Done; return the response. - return response - - def update_tag_key(self, - request: Optional[Union[tag_keys.UpdateTagKeyRequest, dict]] = None, - *, - tag_key: Optional[tag_keys.TagKey] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the attributes of the TagKey resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_update_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.update_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest, dict]): - The request object. The request message for updating a - TagKey. - tag_key (google.cloud.resourcemanager_v3.types.TagKey): - Required. The new definition of the TagKey. Only the - ``description`` and ``etag`` fields can be updated by - this request. If the ``etag`` field is not empty, it - must match the ``etag`` field of the existing tag key. - Otherwise, ``FAILED_PRECONDITION`` will be returned. - - This corresponds to the ``tag_key`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Fields to be updated. The mask may only contain - ``description`` or ``etag``. If omitted entirely, both - ``description`` and ``etag`` are assumed to be - significant. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.resourcemanager_v3.types.TagKey` A - TagKey, used to group a set of TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_keys.UpdateTagKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_keys.UpdateTagKeyRequest): - request = tag_keys.UpdateTagKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_key is not None: - request.tag_key = tag_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_tag_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_key.name", request.tag_key.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - tag_keys.TagKey, - metadata_type=tag_keys.UpdateTagKeyMetadata, - ) - - # Done; return the response. - return response - - def delete_tag_key(self, - request: Optional[Union[tag_keys.DeleteTagKeyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a TagKey. The TagKey cannot be deleted if it - has any child TagValues. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_delete_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagKeyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest, dict]): - The request object. The request message for deleting a - TagKey. - name (str): - Required. The resource name of a TagKey to be deleted in - the format ``tagKeys/123``. The TagKey cannot be a - parent of any existing TagValues or it will not be - deleted successfully. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.resourcemanager_v3.types.TagKey` A - TagKey, used to group a set of TagValues. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_keys.DeleteTagKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_keys.DeleteTagKeyRequest): - request = tag_keys.DeleteTagKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_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), - )), - ) - - # 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, - tag_keys.TagKey, - metadata_type=tag_keys.DeleteTagKeyMetadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for a TagKey. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". The caller must have - ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` - permission on the specified TagKey. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on a TagKey, replacing any - existing policy. The ``resource`` field should be the TagKey's - resource name. For example, "tagKeys/1234". The caller must have - ``resourcemanager.tagKeys.setIamPolicy`` permission on the - identified tagValue. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagKey. - The ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "TagKeysClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "TagKeysClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py deleted file mode 100644 index ca6a02c..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.resourcemanager_v3.types import tag_keys - - -class ListTagKeysPager: - """A pager for iterating through ``list_tag_keys`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tag_keys`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTagKeys`` requests and continue to iterate - through the ``tag_keys`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` - 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[..., tag_keys.ListTagKeysResponse], - request: tag_keys.ListTagKeysRequest, - response: tag_keys.ListTagKeysResponse, - *, - 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.resourcemanager_v3.types.ListTagKeysRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListTagKeysResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tag_keys.ListTagKeysRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[tag_keys.ListTagKeysResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tag_keys.TagKey]: - for page in self.pages: - yield from page.tag_keys - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagKeysAsyncPager: - """A pager for iterating through ``list_tag_keys`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tag_keys`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTagKeys`` requests and continue to iterate - through the ``tag_keys`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagKeysResponse` - 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[tag_keys.ListTagKeysResponse]], - request: tag_keys.ListTagKeysRequest, - response: tag_keys.ListTagKeysResponse, - *, - 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.resourcemanager_v3.types.ListTagKeysRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListTagKeysResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tag_keys.ListTagKeysRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[tag_keys.ListTagKeysResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[tag_keys.TagKey]: - async def async_generator(): - async for page in self.pages: - for response in page.tag_keys: - 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/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py deleted file mode 100644 index 70f0ce8..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import TagKeysTransport -from .grpc import TagKeysGrpcTransport -from .grpc_asyncio import TagKeysGrpcAsyncIOTransport -from .rest import TagKeysRestTransport -from .rest import TagKeysRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TagKeysTransport]] -_transport_registry['grpc'] = TagKeysGrpcTransport -_transport_registry['grpc_asyncio'] = TagKeysGrpcAsyncIOTransport -_transport_registry['rest'] = TagKeysRestTransport - -__all__ = ( - 'TagKeysTransport', - 'TagKeysGrpcTransport', - 'TagKeysGrpcAsyncIOTransport', - 'TagKeysRestTransport', - 'TagKeysRestInterceptor', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py deleted file mode 100644 index be1a3bb..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.resourcemanager_v3 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.resourcemanager_v3.types import tag_keys -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 TagKeysTransport(abc.ABC): - """Abstract transport class for TagKeys.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_tag_keys: gapic_v1.method.wrap_method( - self.list_tag_keys, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_tag_key: gapic_v1.method.wrap_method( - self.get_tag_key, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_tag_key: gapic_v1.method.wrap_method( - self.create_tag_key, - default_timeout=60.0, - client_info=client_info, - ), - self.update_tag_key: gapic_v1.method.wrap_method( - self.update_tag_key, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_tag_key: gapic_v1.method.wrap_method( - self.delete_tag_key, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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 list_tag_keys(self) -> Callable[ - [tag_keys.ListTagKeysRequest], - Union[ - tag_keys.ListTagKeysResponse, - Awaitable[tag_keys.ListTagKeysResponse] - ]]: - raise NotImplementedError() - - @property - def get_tag_key(self) -> Callable[ - [tag_keys.GetTagKeyRequest], - Union[ - tag_keys.TagKey, - Awaitable[tag_keys.TagKey] - ]]: - raise NotImplementedError() - - @property - def create_tag_key(self) -> Callable[ - [tag_keys.CreateTagKeyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_tag_key(self) -> Callable[ - [tag_keys.UpdateTagKeyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_tag_key(self) -> Callable[ - [tag_keys.DeleteTagKeyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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__ = ( - 'TagKeysTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py deleted file mode 100644 index 3bce1f6..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc.py +++ /dev/null @@ -1,487 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_keys -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 TagKeysTransport, DEFAULT_CLIENT_INFO - - -class TagKeysGrpcTransport(TagKeysTransport): - """gRPC backend transport for TagKeys. - - Allow users to create and manage tag keys. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudresourcemanager.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 list_tag_keys(self) -> Callable[ - [tag_keys.ListTagKeysRequest], - tag_keys.ListTagKeysResponse]: - r"""Return a callable for the list tag keys method over gRPC. - - Lists all TagKeys for a parent resource. - - Returns: - Callable[[~.ListTagKeysRequest], - ~.ListTagKeysResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_keys' not in self._stubs: - self._stubs['list_tag_keys'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/ListTagKeys', - request_serializer=tag_keys.ListTagKeysRequest.serialize, - response_deserializer=tag_keys.ListTagKeysResponse.deserialize, - ) - return self._stubs['list_tag_keys'] - - @property - def get_tag_key(self) -> Callable[ - [tag_keys.GetTagKeyRequest], - tag_keys.TagKey]: - r"""Return a callable for the get tag key method over gRPC. - - Retrieves a TagKey. This method will return - ``PERMISSION_DENIED`` if the key does not exist or the user does - not have permission to view it. - - Returns: - Callable[[~.GetTagKeyRequest], - ~.TagKey]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_tag_key' not in self._stubs: - self._stubs['get_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/GetTagKey', - request_serializer=tag_keys.GetTagKeyRequest.serialize, - response_deserializer=tag_keys.TagKey.deserialize, - ) - return self._stubs['get_tag_key'] - - @property - def create_tag_key(self) -> Callable[ - [tag_keys.CreateTagKeyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create tag key method over gRPC. - - Creates a new TagKey. If another request with the - same parameters is sent while the original request is in - process, the second request will receive an error. A - maximum of 300 TagKeys can exist under a parent at any - given time. - - Returns: - Callable[[~.CreateTagKeyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_key' not in self._stubs: - self._stubs['create_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/CreateTagKey', - request_serializer=tag_keys.CreateTagKeyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tag_key'] - - @property - def update_tag_key(self) -> Callable[ - [tag_keys.UpdateTagKeyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update tag key method over gRPC. - - Updates the attributes of the TagKey resource. - - Returns: - Callable[[~.UpdateTagKeyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_key' not in self._stubs: - self._stubs['update_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/UpdateTagKey', - request_serializer=tag_keys.UpdateTagKeyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tag_key'] - - @property - def delete_tag_key(self) -> Callable[ - [tag_keys.DeleteTagKeyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete tag key method over gRPC. - - Deletes a TagKey. The TagKey cannot be deleted if it - has any child TagValues. - - Returns: - Callable[[~.DeleteTagKeyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_tag_key' not in self._stubs: - self._stubs['delete_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/DeleteTagKey', - request_serializer=tag_keys.DeleteTagKeyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tag_key'] - - @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 access control policy for a TagKey. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". The caller must have - ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` - permission on the specified TagKey. - - 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.cloud.resourcemanager.v3.TagKeys/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on a TagKey, replacing any - existing policy. The ``resource`` field should be the TagKey's - resource name. For example, "tagKeys/1234". The caller must have - ``resourcemanager.tagKeys.setIamPolicy`` permission on the - identified tagValue. - - 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.cloud.resourcemanager.v3.TagKeys/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the specified TagKey. - The ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.TagKeys/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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TagKeysGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py deleted file mode 100644 index 20b7bdf..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py +++ /dev/null @@ -1,486 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_keys -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 TagKeysTransport, DEFAULT_CLIENT_INFO -from .grpc import TagKeysGrpcTransport - - -class TagKeysGrpcAsyncIOTransport(TagKeysTransport): - """gRPC AsyncIO backend transport for TagKeys. - - Allow users to create and manage tag keys. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_tag_keys(self) -> Callable[ - [tag_keys.ListTagKeysRequest], - Awaitable[tag_keys.ListTagKeysResponse]]: - r"""Return a callable for the list tag keys method over gRPC. - - Lists all TagKeys for a parent resource. - - Returns: - Callable[[~.ListTagKeysRequest], - Awaitable[~.ListTagKeysResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_keys' not in self._stubs: - self._stubs['list_tag_keys'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/ListTagKeys', - request_serializer=tag_keys.ListTagKeysRequest.serialize, - response_deserializer=tag_keys.ListTagKeysResponse.deserialize, - ) - return self._stubs['list_tag_keys'] - - @property - def get_tag_key(self) -> Callable[ - [tag_keys.GetTagKeyRequest], - Awaitable[tag_keys.TagKey]]: - r"""Return a callable for the get tag key method over gRPC. - - Retrieves a TagKey. This method will return - ``PERMISSION_DENIED`` if the key does not exist or the user does - not have permission to view it. - - Returns: - Callable[[~.GetTagKeyRequest], - Awaitable[~.TagKey]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_tag_key' not in self._stubs: - self._stubs['get_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/GetTagKey', - request_serializer=tag_keys.GetTagKeyRequest.serialize, - response_deserializer=tag_keys.TagKey.deserialize, - ) - return self._stubs['get_tag_key'] - - @property - def create_tag_key(self) -> Callable[ - [tag_keys.CreateTagKeyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create tag key method over gRPC. - - Creates a new TagKey. If another request with the - same parameters is sent while the original request is in - process, the second request will receive an error. A - maximum of 300 TagKeys can exist under a parent at any - given time. - - Returns: - Callable[[~.CreateTagKeyRequest], - 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_tag_key' not in self._stubs: - self._stubs['create_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/CreateTagKey', - request_serializer=tag_keys.CreateTagKeyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tag_key'] - - @property - def update_tag_key(self) -> Callable[ - [tag_keys.UpdateTagKeyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update tag key method over gRPC. - - Updates the attributes of the TagKey resource. - - Returns: - Callable[[~.UpdateTagKeyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_tag_key' not in self._stubs: - self._stubs['update_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/UpdateTagKey', - request_serializer=tag_keys.UpdateTagKeyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tag_key'] - - @property - def delete_tag_key(self) -> Callable[ - [tag_keys.DeleteTagKeyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete tag key method over gRPC. - - Deletes a TagKey. The TagKey cannot be deleted if it - has any child TagValues. - - Returns: - Callable[[~.DeleteTagKeyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_tag_key' not in self._stubs: - self._stubs['delete_tag_key'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagKeys/DeleteTagKey', - request_serializer=tag_keys.DeleteTagKeyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tag_key'] - - @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 access control policy for a TagKey. The returned policy - may be empty if no such policy or resource exists. The - ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". The caller must have - ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy`` - permission on the specified TagKey. - - 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.cloud.resourcemanager.v3.TagKeys/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on a TagKey, replacing any - existing policy. The ``resource`` field should be the TagKey's - resource name. For example, "tagKeys/1234". The caller must have - ``resourcemanager.tagKeys.setIamPolicy`` permission on the - identified tagValue. - - 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.cloud.resourcemanager.v3.TagKeys/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the specified TagKey. - The ``resource`` field should be the TagKey's resource name. For - example, "tagKeys/1234". - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.TagKeys/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'TagKeysGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py deleted file mode 100644 index 27013fc..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py +++ /dev/null @@ -1,1299 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.resourcemanager_v3.types import tag_keys -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 TagKeysTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class TagKeysRestInterceptor: - """Interceptor for TagKeys. - - 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 TagKeysRestTransport. - - .. code-block:: python - class MyCustomTagKeysInterceptor(TagKeysRestInterceptor): - def pre_create_tag_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_tag_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_tag_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_tag_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_tag_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_tag_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tag_keys(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tag_keys(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_tag_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_tag_key(self, response): - logging.log(f"Received response: {response}") - return response - - transport = TagKeysRestTransport(interceptor=MyCustomTagKeysInterceptor()) - client = TagKeysClient(transport=transport) - - - """ - def pre_create_tag_key(self, request: tag_keys.CreateTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.CreateTagKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_tag_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagKeys server. - """ - return request, metadata - - def post_create_tag_key(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_tag_key - - Override in a subclass to manipulate the response - after it is returned by the TagKeys server but before - it is returned to user code. - """ - return response - def pre_delete_tag_key(self, request: tag_keys.DeleteTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.DeleteTagKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_tag_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagKeys server. - """ - return request, metadata - - def post_delete_tag_key(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_tag_key - - Override in a subclass to manipulate the response - after it is returned by the TagKeys 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 TagKeys 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 TagKeys server but before - it is returned to user code. - """ - return response - def pre_get_tag_key(self, request: tag_keys.GetTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.GetTagKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_tag_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagKeys server. - """ - return request, metadata - - def post_get_tag_key(self, response: tag_keys.TagKey) -> tag_keys.TagKey: - """Post-rpc interceptor for get_tag_key - - Override in a subclass to manipulate the response - after it is returned by the TagKeys server but before - it is returned to user code. - """ - return response - def pre_list_tag_keys(self, request: tag_keys.ListTagKeysRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.ListTagKeysRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tag_keys - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagKeys server. - """ - return request, metadata - - def post_list_tag_keys(self, response: tag_keys.ListTagKeysResponse) -> tag_keys.ListTagKeysResponse: - """Post-rpc interceptor for list_tag_keys - - Override in a subclass to manipulate the response - after it is returned by the TagKeys 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 TagKeys 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 TagKeys 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 TagKeys 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 TagKeys server but before - it is returned to user code. - """ - return response - def pre_update_tag_key(self, request: tag_keys.UpdateTagKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_keys.UpdateTagKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_tag_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagKeys server. - """ - return request, metadata - - def post_update_tag_key(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_tag_key - - Override in a subclass to manipulate the response - after it is returned by the TagKeys server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class TagKeysRestStub: - _session: AuthorizedSession - _host: str - _interceptor: TagKeysRestInterceptor - - -class TagKeysRestTransport(TagKeysTransport): - """REST backend transport for TagKeys. - - Allow users to create and manage tag keys. - - 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 = 'cloudresourcemanager.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[TagKeysRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or TagKeysRestInterceptor() - 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': '/v3/{name=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="v3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateTagKey(TagKeysRestStub): - def __hash__(self): - return hash("CreateTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_keys.CreateTagKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create tag key method over HTTP. - - Args: - request (~.tag_keys.CreateTagKeyRequest): - The request object. The request message for creating a - TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/tagKeys', - 'body': 'tag_key', - }, - ] - request, metadata = self._interceptor.pre_create_tag_key(request, metadata) - pb_request = tag_keys.CreateTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_tag_key(resp) - return resp - - class _DeleteTagKey(TagKeysRestStub): - def __hash__(self): - return hash("DeleteTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_keys.DeleteTagKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete tag key method over HTTP. - - Args: - request (~.tag_keys.DeleteTagKeyRequest): - The request object. The request message for deleting a - TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v3/{name=tagKeys/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_tag_key(request, metadata) - pb_request = tag_keys.DeleteTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_tag_key(resp) - return resp - - class _GetIamPolicy(TagKeysRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=tagKeys/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetTagKey(TagKeysRestStub): - def __hash__(self): - return hash("GetTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_keys.GetTagKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tag_keys.TagKey: - r"""Call the get tag key method over HTTP. - - Args: - request (~.tag_keys.GetTagKeyRequest): - The request object. The request message for getting a - TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tag_keys.TagKey: - A TagKey, used to group a set of - TagValues. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/{name=tagKeys/*}', - }, - ] - request, metadata = self._interceptor.pre_get_tag_key(request, metadata) - pb_request = tag_keys.GetTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tag_keys.TagKey() - pb_resp = tag_keys.TagKey.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_tag_key(resp) - return resp - - class _ListTagKeys(TagKeysRestStub): - def __hash__(self): - return hash("ListTagKeys") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_keys.ListTagKeysRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tag_keys.ListTagKeysResponse: - r"""Call the list tag keys method over HTTP. - - Args: - request (~.tag_keys.ListTagKeysRequest): - The request object. The request message for listing all - TagKeys under a parent resource. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tag_keys.ListTagKeysResponse: - The ListTagKeys response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/tagKeys', - }, - ] - request, metadata = self._interceptor.pre_list_tag_keys(request, metadata) - pb_request = tag_keys.ListTagKeysRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tag_keys.ListTagKeysResponse() - pb_resp = tag_keys.ListTagKeysResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tag_keys(resp) - return resp - - class _SetIamPolicy(TagKeysRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=tagKeys/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(TagKeysRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=tagKeys/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateTagKey(TagKeysRestStub): - def __hash__(self): - return hash("UpdateTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_keys.UpdateTagKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update tag key method over HTTP. - - Args: - request (~.tag_keys.UpdateTagKeyRequest): - The request object. The request message for updating a - TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v3/{tag_key.name=tagKeys/*}', - 'body': 'tag_key', - }, - ] - request, metadata = self._interceptor.pre_update_tag_key(request, metadata) - pb_request = tag_keys.UpdateTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_tag_key(resp) - return resp - - @property - def create_tag_key(self) -> Callable[ - [tag_keys.CreateTagKeyRequest], - 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._CreateTagKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_tag_key(self) -> Callable[ - [tag_keys.DeleteTagKeyRequest], - 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._DeleteTagKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_tag_key(self) -> Callable[ - [tag_keys.GetTagKeyRequest], - tag_keys.TagKey]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetTagKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tag_keys(self) -> Callable[ - [tag_keys.ListTagKeysRequest], - tag_keys.ListTagKeysResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListTagKeys(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_tag_key(self) -> Callable[ - [tag_keys.UpdateTagKeyRequest], - 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._UpdateTagKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'TagKeysRestTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py deleted file mode 100644 index e1300af..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import TagValuesClient -from .async_client import TagValuesAsyncClient - -__all__ = ( - 'TagValuesClient', - 'TagValuesAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py deleted file mode 100644 index e0822b4..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/async_client.py +++ /dev/null @@ -1,1247 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.tag_values import pagers -from google.cloud.resourcemanager_v3.types import tag_values -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TagValuesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TagValuesGrpcAsyncIOTransport -from .client import TagValuesClient - - -class TagValuesAsyncClient: - """Allow users to create and manage tag values.""" - - _client: TagValuesClient - - DEFAULT_ENDPOINT = TagValuesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TagValuesClient.DEFAULT_MTLS_ENDPOINT - - tag_value_path = staticmethod(TagValuesClient.tag_value_path) - parse_tag_value_path = staticmethod(TagValuesClient.parse_tag_value_path) - common_billing_account_path = staticmethod(TagValuesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TagValuesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TagValuesClient.common_folder_path) - parse_common_folder_path = staticmethod(TagValuesClient.parse_common_folder_path) - common_organization_path = staticmethod(TagValuesClient.common_organization_path) - parse_common_organization_path = staticmethod(TagValuesClient.parse_common_organization_path) - common_project_path = staticmethod(TagValuesClient.common_project_path) - parse_common_project_path = staticmethod(TagValuesClient.parse_common_project_path) - common_location_path = staticmethod(TagValuesClient.common_location_path) - parse_common_location_path = staticmethod(TagValuesClient.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: - TagValuesAsyncClient: The constructed client. - """ - return TagValuesClient.from_service_account_info.__func__(TagValuesAsyncClient, 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: - TagValuesAsyncClient: The constructed client. - """ - return TagValuesClient.from_service_account_file.__func__(TagValuesAsyncClient, 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 TagValuesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TagValuesTransport: - """Returns the transport used by the client instance. - - Returns: - TagValuesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TagValuesClient).get_transport_class, type(TagValuesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, TagValuesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the tag values client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.TagValuesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = TagValuesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_tag_values(self, - request: Optional[Union[tag_values.ListTagValuesRequest, 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.ListTagValuesAsyncPager: - r"""Lists all TagValues for a specific TagKey. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_list_tag_values(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagValuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_values(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagValuesRequest, dict]]): - The request object. The request message for listing - TagValues for the specified TagKey. - parent (:class:`str`): - Required. Resource name for TagKey, parent of the - TagValues to be listed, in the format ``tagKeys/123``. - - 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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesAsyncPager: - The ListTagValues response. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_values.ListTagValuesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_tag_values, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListTagValuesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_tag_value(self, - request: Optional[Union[tag_values.GetTagValueRequest, 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]] = (), - ) -> tag_values.TagValue: - r"""Retrieves TagValue. If the TagValue or namespaced name does not - exist, or if the user does not have permission to view it, this - method will return ``PERMISSION_DENIED``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_get_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagValueRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tag_value(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.GetTagValueRequest, dict]]): - The request object. The request message for getting a - TagValue. - name (:class:`str`): - Required. Resource name for TagValue to be fetched in - the format ``tagValues/456``. - - 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.resourcemanager_v3.types.TagValue: - A TagValue is a child of a particular - TagKey. This is used to group cloud - resources for the purpose of controlling - them using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_values.GetTagValueRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_tag_value, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_tag_value(self, - request: Optional[Union[tag_values.CreateTagValueRequest, dict]] = None, - *, - tag_value: Optional[tag_values.TagValue] = 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 TagValue as a child of the specified - TagKey. If a another request with the same parameters is - sent while the original request is in process the second - request will receive an error. A maximum of 300 - TagValues can exist under a TagKey at any given time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_create_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.create_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagValueRequest, dict]]): - The request object. The request message for creating a - TagValue. - tag_value (:class:`google.cloud.resourcemanager_v3.types.TagValue`): - Required. The TagValue to be created. Only fields - ``short_name``, ``description``, and ``parent`` are - considered during the creation request. - - This corresponds to the ``tag_value`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group - cloud resources for the purpose of controlling them - using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_value]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_values.CreateTagValueRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_value is not None: - request.tag_value = tag_value - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_tag_value, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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, - tag_values.TagValue, - metadata_type=tag_values.CreateTagValueMetadata, - ) - - # Done; return the response. - return response - - async def update_tag_value(self, - request: Optional[Union[tag_values.UpdateTagValueRequest, dict]] = None, - *, - tag_value: Optional[tag_values.TagValue] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the attributes of the TagValue resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_update_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.update_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.UpdateTagValueRequest, dict]]): - The request object. The request message for updating a - TagValue. - tag_value (:class:`google.cloud.resourcemanager_v3.types.TagValue`): - Required. The new definition of the TagValue. Only - fields ``description`` and ``etag`` fields can be - updated by this request. If the ``etag`` field is - nonempty, it must match the ``etag`` field of the - existing ControlGroup. Otherwise, - ``FAILED_PRECONDITION`` will be returned. - - This corresponds to the ``tag_value`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Fields to be updated. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group - cloud resources for the purpose of controlling them - using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_value, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_values.UpdateTagValueRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_value is not None: - request.tag_value = tag_value - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_tag_value, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_value.name", request.tag_value.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - tag_values.TagValue, - metadata_type=tag_values.UpdateTagValueMetadata, - ) - - # Done; return the response. - return response - - async def delete_tag_value(self, - request: Optional[Union[tag_values.DeleteTagValueRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a TagValue. The TagValue cannot have any - bindings when it is deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - async def sample_delete_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagValueRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagValueRequest, dict]]): - The request object. The request message for deleting a - TagValue. - name (:class:`str`): - Required. Resource name for TagValue - to be deleted in the format - tagValues/456. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group - cloud resources for the purpose of controlling them - using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = tag_values.DeleteTagValueRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_tag_value, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - tag_values.TagValue, - metadata_type=tag_values.DeleteTagValueMetadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for a TagValue. The returned - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the TagValue's resource name. For - example: ``tagValues/1234``. The caller must have the - ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` - permission on the identified TagValue to get the access control - policy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on a TagValue, replacing any - existing policy. The ``resource`` field should be the TagValue's - resource name. For example: ``tagValues/1234``. The caller must - have ``resourcemanager.tagValues.setIamPolicy`` permission on - the identified tagValue. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=DEFAULT_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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagValue. - The ``resource`` field should be the TagValue's resource name. - For example: ``tagValues/1234``. - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._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), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "TagValuesAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py deleted file mode 100644 index 2d19968..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/client.py +++ /dev/null @@ -1,1432 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.resourcemanager_v3 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.resourcemanager_v3.services.tag_values import pagers -from google.cloud.resourcemanager_v3.types import tag_values -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TagValuesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TagValuesGrpcTransport -from .transports.grpc_asyncio import TagValuesGrpcAsyncIOTransport -from .transports.rest import TagValuesRestTransport - - -class TagValuesClientMeta(type): - """Metaclass for the TagValues 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[TagValuesTransport]] - _transport_registry["grpc"] = TagValuesGrpcTransport - _transport_registry["grpc_asyncio"] = TagValuesGrpcAsyncIOTransport - _transport_registry["rest"] = TagValuesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TagValuesTransport]: - """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 TagValuesClient(metaclass=TagValuesClientMeta): - """Allow users to create and manage tag values.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - TagValuesClient: 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: - TagValuesClient: 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) -> TagValuesTransport: - """Returns the transport used by the client instance. - - Returns: - TagValuesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def tag_value_path(tag_value: str,) -> str: - """Returns a fully-qualified tag_value string.""" - return "tagValues/{tag_value}".format(tag_value=tag_value, ) - - @staticmethod - def parse_tag_value_path(path: str) -> Dict[str,str]: - """Parses a tag_value path into its component segments.""" - m = re.match(r"^tagValues/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TagValuesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the tag values client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, TagValuesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, TagValuesTransport): - # transport is a TagValuesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_tag_values(self, - request: Optional[Union[tag_values.ListTagValuesRequest, 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.ListTagValuesPager: - r"""Lists all TagValues for a specific TagKey. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_list_tag_values(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagValuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_values(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.ListTagValuesRequest, dict]): - The request object. The request message for listing - TagValues for the specified TagKey. - parent (str): - Required. Resource name for TagKey, parent of the - TagValues to be listed, in the format ``tagKeys/123``. - - 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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesPager: - The ListTagValues response. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_values.ListTagValuesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_values.ListTagValuesRequest): - request = tag_values.ListTagValuesRequest(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_tag_values] - - # 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.ListTagValuesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_tag_value(self, - request: Optional[Union[tag_values.GetTagValueRequest, 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]] = (), - ) -> tag_values.TagValue: - r"""Retrieves TagValue. If the TagValue or namespaced name does not - exist, or if the user does not have permission to view it, this - method will return ``PERMISSION_DENIED``. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_get_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagValueRequest( - name="name_value", - ) - - # Make the request - response = client.get_tag_value(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.GetTagValueRequest, dict]): - The request object. The request message for getting a - TagValue. - name (str): - Required. Resource name for TagValue to be fetched in - the format ``tagValues/456``. - - 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.resourcemanager_v3.types.TagValue: - A TagValue is a child of a particular - TagKey. This is used to group cloud - resources for the purpose of controlling - them using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_values.GetTagValueRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_values.GetTagValueRequest): - request = tag_values.GetTagValueRequest(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_tag_value] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_tag_value(self, - request: Optional[Union[tag_values.CreateTagValueRequest, dict]] = None, - *, - tag_value: Optional[tag_values.TagValue] = 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 TagValue as a child of the specified - TagKey. If a another request with the same parameters is - sent while the original request is in process the second - request will receive an error. A maximum of 300 - TagValues can exist under a TagKey at any given time. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_create_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.create_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.CreateTagValueRequest, dict]): - The request object. The request message for creating a - TagValue. - tag_value (google.cloud.resourcemanager_v3.types.TagValue): - Required. The TagValue to be created. Only fields - ``short_name``, ``description``, and ``parent`` are - considered during the creation request. - - This corresponds to the ``tag_value`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group - cloud resources for the purpose of controlling them - using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_value]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_values.CreateTagValueRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_values.CreateTagValueRequest): - request = tag_values.CreateTagValueRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_value is not None: - request.tag_value = tag_value - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_tag_value] - - # 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, - tag_values.TagValue, - metadata_type=tag_values.CreateTagValueMetadata, - ) - - # Done; return the response. - return response - - def update_tag_value(self, - request: Optional[Union[tag_values.UpdateTagValueRequest, dict]] = None, - *, - tag_value: Optional[tag_values.TagValue] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the attributes of the TagValue resource. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_update_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.update_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.UpdateTagValueRequest, dict]): - The request object. The request message for updating a - TagValue. - tag_value (google.cloud.resourcemanager_v3.types.TagValue): - Required. The new definition of the TagValue. Only - fields ``description`` and ``etag`` fields can be - updated by this request. If the ``etag`` field is - nonempty, it must match the ``etag`` field of the - existing ControlGroup. Otherwise, - ``FAILED_PRECONDITION`` will be returned. - - This corresponds to the ``tag_value`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Fields to be updated. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group - cloud resources for the purpose of controlling them - using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([tag_value, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_values.UpdateTagValueRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_values.UpdateTagValueRequest): - request = tag_values.UpdateTagValueRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if tag_value is not None: - request.tag_value = tag_value - 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_tag_value] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("tag_value.name", request.tag_value.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - tag_values.TagValue, - metadata_type=tag_values.UpdateTagValueMetadata, - ) - - # Done; return the response. - return response - - def delete_tag_value(self, - request: Optional[Union[tag_values.DeleteTagValueRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a TagValue. The TagValue cannot have any - bindings when it is deleted. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - - def sample_delete_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagValueRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.resourcemanager_v3.types.DeleteTagValueRequest, dict]): - The request object. The request message for deleting a - TagValue. - name (str): - Required. Resource name for TagValue - to be deleted in the format - tagValues/456. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagValue` A TagValue is a child of a particular TagKey. This is used to group - cloud resources for the purpose of controlling them - using policies. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a tag_values.DeleteTagValueRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, tag_values.DeleteTagValueRequest): - request = tag_values.DeleteTagValueRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_tag_value] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - tag_values.TagValue, - metadata_type=tag_values.DeleteTagValueMetadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy for a TagValue. The returned - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the TagValue's resource name. For - example: ``tagValues/1234``. The caller must have the - ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` - permission on the identified TagValue to get the access control - policy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = 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 access control policy on a TagValue, replacing any - existing policy. The ``resource`` field should be the TagValue's - resource name. For example: ``tagValues/1234``. The caller must - have ``resourcemanager.tagValues.setIamPolicy`` permission on - the identified tagValue. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **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')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **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') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # 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[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = 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"""Returns permissions that a caller has on the specified TagValue. - The ``resource`` field should be the TagValue's resource name. - For example: ``tagValues/1234``. - - There are no permissions required for making this API call. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import resourcemanager_v3 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "TagValuesClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "TagValuesClient", -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py deleted file mode 100644 index 9094cf9..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.resourcemanager_v3.types import tag_values - - -class ListTagValuesPager: - """A pager for iterating through ``list_tag_values`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tag_values`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTagValues`` requests and continue to iterate - through the ``tag_values`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` - 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[..., tag_values.ListTagValuesResponse], - request: tag_values.ListTagValuesRequest, - response: tag_values.ListTagValuesResponse, - *, - 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.resourcemanager_v3.types.ListTagValuesRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListTagValuesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tag_values.ListTagValuesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[tag_values.ListTagValuesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tag_values.TagValue]: - for page in self.pages: - yield from page.tag_values - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTagValuesAsyncPager: - """A pager for iterating through ``list_tag_values`` requests. - - This class thinly wraps an initial - :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tag_values`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTagValues`` requests and continue to iterate - through the ``tag_values`` field on the - corresponding responses. - - All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagValuesResponse` - 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[tag_values.ListTagValuesResponse]], - request: tag_values.ListTagValuesRequest, - response: tag_values.ListTagValuesResponse, - *, - 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.resourcemanager_v3.types.ListTagValuesRequest): - The initial request object. - response (google.cloud.resourcemanager_v3.types.ListTagValuesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = tag_values.ListTagValuesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[tag_values.ListTagValuesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[tag_values.TagValue]: - async def async_generator(): - async for page in self.pages: - for response in page.tag_values: - 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/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py deleted file mode 100644 index 0eed143..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import TagValuesTransport -from .grpc import TagValuesGrpcTransport -from .grpc_asyncio import TagValuesGrpcAsyncIOTransport -from .rest import TagValuesRestTransport -from .rest import TagValuesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TagValuesTransport]] -_transport_registry['grpc'] = TagValuesGrpcTransport -_transport_registry['grpc_asyncio'] = TagValuesGrpcAsyncIOTransport -_transport_registry['rest'] = TagValuesRestTransport - -__all__ = ( - 'TagValuesTransport', - 'TagValuesGrpcTransport', - 'TagValuesGrpcAsyncIOTransport', - 'TagValuesRestTransport', - 'TagValuesRestInterceptor', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py deleted file mode 100644 index 3b8cf01..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py +++ /dev/null @@ -1,274 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.resourcemanager_v3 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.resourcemanager_v3.types import tag_values -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 TagValuesTransport(abc.ABC): - """Abstract transport class for TagValues.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'cloudresourcemanager.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_tag_values: gapic_v1.method.wrap_method( - self.list_tag_values, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_tag_value: gapic_v1.method.wrap_method( - self.get_tag_value, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_tag_value: gapic_v1.method.wrap_method( - self.create_tag_value, - default_timeout=60.0, - client_info=client_info, - ), - self.update_tag_value: gapic_v1.method.wrap_method( - self.update_tag_value, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_tag_value: gapic_v1.method.wrap_method( - self.delete_tag_value, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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 list_tag_values(self) -> Callable[ - [tag_values.ListTagValuesRequest], - Union[ - tag_values.ListTagValuesResponse, - Awaitable[tag_values.ListTagValuesResponse] - ]]: - raise NotImplementedError() - - @property - def get_tag_value(self) -> Callable[ - [tag_values.GetTagValueRequest], - Union[ - tag_values.TagValue, - Awaitable[tag_values.TagValue] - ]]: - raise NotImplementedError() - - @property - def create_tag_value(self) -> Callable[ - [tag_values.CreateTagValueRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_tag_value(self) -> Callable[ - [tag_values.UpdateTagValueRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_tag_value(self) -> Callable[ - [tag_values.DeleteTagValueRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - 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 set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - 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__ = ( - 'TagValuesTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py deleted file mode 100644 index 252b229..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc.py +++ /dev/null @@ -1,488 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_values -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 TagValuesTransport, DEFAULT_CLIENT_INFO - - -class TagValuesGrpcTransport(TagValuesTransport): - """gRPC backend transport for TagValues. - - Allow users to create and manage tag values. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudresourcemanager.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 list_tag_values(self) -> Callable[ - [tag_values.ListTagValuesRequest], - tag_values.ListTagValuesResponse]: - r"""Return a callable for the list tag values method over gRPC. - - Lists all TagValues for a specific TagKey. - - Returns: - Callable[[~.ListTagValuesRequest], - ~.ListTagValuesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_values' not in self._stubs: - self._stubs['list_tag_values'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/ListTagValues', - request_serializer=tag_values.ListTagValuesRequest.serialize, - response_deserializer=tag_values.ListTagValuesResponse.deserialize, - ) - return self._stubs['list_tag_values'] - - @property - def get_tag_value(self) -> Callable[ - [tag_values.GetTagValueRequest], - tag_values.TagValue]: - r"""Return a callable for the get tag value method over gRPC. - - Retrieves TagValue. If the TagValue or namespaced name does not - exist, or if the user does not have permission to view it, this - method will return ``PERMISSION_DENIED``. - - Returns: - Callable[[~.GetTagValueRequest], - ~.TagValue]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_tag_value' not in self._stubs: - self._stubs['get_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/GetTagValue', - request_serializer=tag_values.GetTagValueRequest.serialize, - response_deserializer=tag_values.TagValue.deserialize, - ) - return self._stubs['get_tag_value'] - - @property - def create_tag_value(self) -> Callable[ - [tag_values.CreateTagValueRequest], - operations_pb2.Operation]: - r"""Return a callable for the create tag value method over gRPC. - - Creates a TagValue as a child of the specified - TagKey. If a another request with the same parameters is - sent while the original request is in process the second - request will receive an error. A maximum of 300 - TagValues can exist under a TagKey at any given time. - - Returns: - Callable[[~.CreateTagValueRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_value' not in self._stubs: - self._stubs['create_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/CreateTagValue', - request_serializer=tag_values.CreateTagValueRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tag_value'] - - @property - def update_tag_value(self) -> Callable[ - [tag_values.UpdateTagValueRequest], - operations_pb2.Operation]: - r"""Return a callable for the update tag value method over gRPC. - - Updates the attributes of the TagValue resource. - - Returns: - Callable[[~.UpdateTagValueRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_value' not in self._stubs: - self._stubs['update_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/UpdateTagValue', - request_serializer=tag_values.UpdateTagValueRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tag_value'] - - @property - def delete_tag_value(self) -> Callable[ - [tag_values.DeleteTagValueRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete tag value method over gRPC. - - Deletes a TagValue. The TagValue cannot have any - bindings when it is deleted. - - Returns: - Callable[[~.DeleteTagValueRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_tag_value' not in self._stubs: - self._stubs['delete_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/DeleteTagValue', - request_serializer=tag_values.DeleteTagValueRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tag_value'] - - @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 access control policy for a TagValue. The returned - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the TagValue's resource name. For - example: ``tagValues/1234``. The caller must have the - ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` - permission on the identified TagValue to get the access control - policy. - - 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.cloud.resourcemanager.v3.TagValues/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on a TagValue, replacing any - existing policy. The ``resource`` field should be the TagValue's - resource name. For example: ``tagValues/1234``. The caller must - have ``resourcemanager.tagValues.setIamPolicy`` permission on - the identified tagValue. - - 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.cloud.resourcemanager.v3.TagValues/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the specified TagValue. - The ``resource`` field should be the TagValue's resource name. - For example: ``tagValues/1234``. - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.TagValues/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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TagValuesGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py deleted file mode 100644 index 5f588c8..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py +++ /dev/null @@ -1,487 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_values -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 TagValuesTransport, DEFAULT_CLIENT_INFO -from .grpc import TagValuesGrpcTransport - - -class TagValuesGrpcAsyncIOTransport(TagValuesTransport): - """gRPC AsyncIO backend transport for TagValues. - - Allow users to create and manage tag values. - - 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 = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudresourcemanager.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_tag_values(self) -> Callable[ - [tag_values.ListTagValuesRequest], - Awaitable[tag_values.ListTagValuesResponse]]: - r"""Return a callable for the list tag values method over gRPC. - - Lists all TagValues for a specific TagKey. - - Returns: - Callable[[~.ListTagValuesRequest], - Awaitable[~.ListTagValuesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_tag_values' not in self._stubs: - self._stubs['list_tag_values'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/ListTagValues', - request_serializer=tag_values.ListTagValuesRequest.serialize, - response_deserializer=tag_values.ListTagValuesResponse.deserialize, - ) - return self._stubs['list_tag_values'] - - @property - def get_tag_value(self) -> Callable[ - [tag_values.GetTagValueRequest], - Awaitable[tag_values.TagValue]]: - r"""Return a callable for the get tag value method over gRPC. - - Retrieves TagValue. If the TagValue or namespaced name does not - exist, or if the user does not have permission to view it, this - method will return ``PERMISSION_DENIED``. - - Returns: - Callable[[~.GetTagValueRequest], - Awaitable[~.TagValue]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_tag_value' not in self._stubs: - self._stubs['get_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/GetTagValue', - request_serializer=tag_values.GetTagValueRequest.serialize, - response_deserializer=tag_values.TagValue.deserialize, - ) - return self._stubs['get_tag_value'] - - @property - def create_tag_value(self) -> Callable[ - [tag_values.CreateTagValueRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create tag value method over gRPC. - - Creates a TagValue as a child of the specified - TagKey. If a another request with the same parameters is - sent while the original request is in process the second - request will receive an error. A maximum of 300 - TagValues can exist under a TagKey at any given time. - - Returns: - Callable[[~.CreateTagValueRequest], - 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_tag_value' not in self._stubs: - self._stubs['create_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/CreateTagValue', - request_serializer=tag_values.CreateTagValueRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_tag_value'] - - @property - def update_tag_value(self) -> Callable[ - [tag_values.UpdateTagValueRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update tag value method over gRPC. - - Updates the attributes of the TagValue resource. - - Returns: - Callable[[~.UpdateTagValueRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_tag_value' not in self._stubs: - self._stubs['update_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/UpdateTagValue', - request_serializer=tag_values.UpdateTagValueRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_tag_value'] - - @property - def delete_tag_value(self) -> Callable[ - [tag_values.DeleteTagValueRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete tag value method over gRPC. - - Deletes a TagValue. The TagValue cannot have any - bindings when it is deleted. - - Returns: - Callable[[~.DeleteTagValueRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_tag_value' not in self._stubs: - self._stubs['delete_tag_value'] = self.grpc_channel.unary_unary( - '/google.cloud.resourcemanager.v3.TagValues/DeleteTagValue', - request_serializer=tag_values.DeleteTagValueRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_tag_value'] - - @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 access control policy for a TagValue. The returned - policy may be empty if no such policy or resource exists. The - ``resource`` field should be the TagValue's resource name. For - example: ``tagValues/1234``. The caller must have the - ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy`` - permission on the identified TagValue to get the access control - policy. - - 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.cloud.resourcemanager.v3.TagValues/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @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 access control policy on a TagValue, replacing any - existing policy. The ``resource`` field should be the TagValue's - resource name. For example: ``tagValues/1234``. The caller must - have ``resourcemanager.tagValues.setIamPolicy`` permission on - the identified tagValue. - - 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.cloud.resourcemanager.v3.TagValues/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns permissions that a caller has on the specified TagValue. - The ``resource`` field should be the TagValue's resource name. - For example: ``tagValues/1234``. - - There are no permissions required for making this API call. - - 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.cloud.resourcemanager.v3.TagValues/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'TagValuesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py deleted file mode 100644 index 71fc337..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py +++ /dev/null @@ -1,1301 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.resourcemanager_v3.types import tag_values -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 TagValuesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class TagValuesRestInterceptor: - """Interceptor for TagValues. - - 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 TagValuesRestTransport. - - .. code-block:: python - class MyCustomTagValuesInterceptor(TagValuesRestInterceptor): - def pre_create_tag_value(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_tag_value(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_tag_value(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_tag_value(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_tag_value(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_tag_value(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tag_values(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tag_values(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_tag_value(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_tag_value(self, response): - logging.log(f"Received response: {response}") - return response - - transport = TagValuesRestTransport(interceptor=MyCustomTagValuesInterceptor()) - client = TagValuesClient(transport=transport) - - - """ - def pre_create_tag_value(self, request: tag_values.CreateTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.CreateTagValueRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_tag_value - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagValues server. - """ - return request, metadata - - def post_create_tag_value(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_tag_value - - Override in a subclass to manipulate the response - after it is returned by the TagValues server but before - it is returned to user code. - """ - return response - def pre_delete_tag_value(self, request: tag_values.DeleteTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.DeleteTagValueRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_tag_value - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagValues server. - """ - return request, metadata - - def post_delete_tag_value(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_tag_value - - Override in a subclass to manipulate the response - after it is returned by the TagValues 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 TagValues 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 TagValues server but before - it is returned to user code. - """ - return response - def pre_get_tag_value(self, request: tag_values.GetTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.GetTagValueRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_tag_value - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagValues server. - """ - return request, metadata - - def post_get_tag_value(self, response: tag_values.TagValue) -> tag_values.TagValue: - """Post-rpc interceptor for get_tag_value - - Override in a subclass to manipulate the response - after it is returned by the TagValues server but before - it is returned to user code. - """ - return response - def pre_list_tag_values(self, request: tag_values.ListTagValuesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.ListTagValuesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tag_values - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagValues server. - """ - return request, metadata - - def post_list_tag_values(self, response: tag_values.ListTagValuesResponse) -> tag_values.ListTagValuesResponse: - """Post-rpc interceptor for list_tag_values - - Override in a subclass to manipulate the response - after it is returned by the TagValues 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 TagValues 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 TagValues 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 TagValues 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 TagValues server but before - it is returned to user code. - """ - return response - def pre_update_tag_value(self, request: tag_values.UpdateTagValueRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[tag_values.UpdateTagValueRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_tag_value - - Override in a subclass to manipulate the request or metadata - before they are sent to the TagValues server. - """ - return request, metadata - - def post_update_tag_value(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_tag_value - - Override in a subclass to manipulate the response - after it is returned by the TagValues server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class TagValuesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: TagValuesRestInterceptor - - -class TagValuesRestTransport(TagValuesTransport): - """REST backend transport for TagValues. - - Allow users to create and manage tag values. - - 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 = 'cloudresourcemanager.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[TagValuesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or TagValuesRestInterceptor() - 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': '/v3/{name=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="v3") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateTagValue(TagValuesRestStub): - def __hash__(self): - return hash("CreateTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_values.CreateTagValueRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create tag value method over HTTP. - - Args: - request (~.tag_values.CreateTagValueRequest): - The request object. The request message for creating a - TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/tagValues', - 'body': 'tag_value', - }, - ] - request, metadata = self._interceptor.pre_create_tag_value(request, metadata) - pb_request = tag_values.CreateTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_tag_value(resp) - return resp - - class _DeleteTagValue(TagValuesRestStub): - def __hash__(self): - return hash("DeleteTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_values.DeleteTagValueRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete tag value method over HTTP. - - Args: - request (~.tag_values.DeleteTagValueRequest): - The request object. The request message for deleting a - TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v3/{name=tagValues/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_tag_value(request, metadata) - pb_request = tag_values.DeleteTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_tag_value(resp) - return resp - - class _GetIamPolicy(TagValuesRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=tagValues/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _GetTagValue(TagValuesRestStub): - def __hash__(self): - return hash("GetTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_values.GetTagValueRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tag_values.TagValue: - r"""Call the get tag value method over HTTP. - - Args: - request (~.tag_values.GetTagValueRequest): - The request object. The request message for getting a - TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tag_values.TagValue: - A TagValue is a child of a particular - TagKey. This is used to group cloud - resources for the purpose of controlling - them using policies. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/{name=tagValues/*}', - }, - ] - request, metadata = self._interceptor.pre_get_tag_value(request, metadata) - pb_request = tag_values.GetTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tag_values.TagValue() - pb_resp = tag_values.TagValue.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_tag_value(resp) - return resp - - class _ListTagValues(TagValuesRestStub): - def __hash__(self): - return hash("ListTagValues") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_values.ListTagValuesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tag_values.ListTagValuesResponse: - r"""Call the list tag values method over HTTP. - - Args: - request (~.tag_values.ListTagValuesRequest): - The request object. The request message for listing - TagValues for the specified TagKey. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.tag_values.ListTagValuesResponse: - The ListTagValues response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v3/tagValues', - }, - ] - request, metadata = self._interceptor.pre_list_tag_values(request, metadata) - pb_request = tag_values.ListTagValuesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tag_values.ListTagValuesResponse() - pb_resp = tag_values.ListTagValuesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tag_values(resp) - return resp - - class _SetIamPolicy(TagValuesRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **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')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **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') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=tagValues/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(TagValuesRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: 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. 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v3/{resource=tagValues/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UpdateTagValue(TagValuesRestStub): - def __hash__(self): - return hash("UpdateTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: tag_values.UpdateTagValueRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update tag value method over HTTP. - - Args: - request (~.tag_values.UpdateTagValueRequest): - The request object. The request message for updating a - TagValue. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v3/{tag_value.name=tagValues/*}', - 'body': 'tag_value', - }, - ] - request, metadata = self._interceptor.pre_update_tag_value(request, metadata) - pb_request = tag_values.UpdateTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_tag_value(resp) - return resp - - @property - def create_tag_value(self) -> Callable[ - [tag_values.CreateTagValueRequest], - 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._CreateTagValue(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_tag_value(self) -> Callable[ - [tag_values.DeleteTagValueRequest], - 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._DeleteTagValue(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_tag_value(self) -> Callable[ - [tag_values.GetTagValueRequest], - tag_values.TagValue]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetTagValue(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tag_values(self) -> Callable[ - [tag_values.ListTagValuesRequest], - tag_values.ListTagValuesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListTagValues(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_tag_value(self) -> Callable[ - [tag_values.UpdateTagValueRequest], - 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._UpdateTagValue(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'TagValuesRestTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py deleted file mode 100644 index 37c36b4..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/__init__.py +++ /dev/null @@ -1,160 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .folders import ( - CreateFolderMetadata, - CreateFolderRequest, - DeleteFolderMetadata, - DeleteFolderRequest, - Folder, - GetFolderRequest, - ListFoldersRequest, - ListFoldersResponse, - MoveFolderMetadata, - MoveFolderRequest, - SearchFoldersRequest, - SearchFoldersResponse, - UndeleteFolderMetadata, - UndeleteFolderRequest, - UpdateFolderMetadata, - UpdateFolderRequest, -) -from .organizations import ( - DeleteOrganizationMetadata, - GetOrganizationRequest, - Organization, - SearchOrganizationsRequest, - SearchOrganizationsResponse, - UndeleteOrganizationMetadata, -) -from .projects import ( - CreateProjectMetadata, - CreateProjectRequest, - DeleteProjectMetadata, - DeleteProjectRequest, - GetProjectRequest, - ListProjectsRequest, - ListProjectsResponse, - MoveProjectMetadata, - MoveProjectRequest, - Project, - SearchProjectsRequest, - SearchProjectsResponse, - UndeleteProjectMetadata, - UndeleteProjectRequest, - UpdateProjectMetadata, - UpdateProjectRequest, -) -from .tag_bindings import ( - CreateTagBindingMetadata, - CreateTagBindingRequest, - DeleteTagBindingMetadata, - DeleteTagBindingRequest, - ListTagBindingsRequest, - ListTagBindingsResponse, - TagBinding, -) -from .tag_keys import ( - CreateTagKeyMetadata, - CreateTagKeyRequest, - DeleteTagKeyMetadata, - DeleteTagKeyRequest, - GetTagKeyRequest, - ListTagKeysRequest, - ListTagKeysResponse, - TagKey, - UpdateTagKeyMetadata, - UpdateTagKeyRequest, -) -from .tag_values import ( - CreateTagValueMetadata, - CreateTagValueRequest, - DeleteTagValueMetadata, - DeleteTagValueRequest, - GetTagValueRequest, - ListTagValuesRequest, - ListTagValuesResponse, - TagValue, - UpdateTagValueMetadata, - UpdateTagValueRequest, -) - -__all__ = ( - 'CreateFolderMetadata', - 'CreateFolderRequest', - 'DeleteFolderMetadata', - 'DeleteFolderRequest', - 'Folder', - 'GetFolderRequest', - 'ListFoldersRequest', - 'ListFoldersResponse', - 'MoveFolderMetadata', - 'MoveFolderRequest', - 'SearchFoldersRequest', - 'SearchFoldersResponse', - 'UndeleteFolderMetadata', - 'UndeleteFolderRequest', - 'UpdateFolderMetadata', - 'UpdateFolderRequest', - 'DeleteOrganizationMetadata', - 'GetOrganizationRequest', - 'Organization', - 'SearchOrganizationsRequest', - 'SearchOrganizationsResponse', - 'UndeleteOrganizationMetadata', - 'CreateProjectMetadata', - 'CreateProjectRequest', - 'DeleteProjectMetadata', - 'DeleteProjectRequest', - 'GetProjectRequest', - 'ListProjectsRequest', - 'ListProjectsResponse', - 'MoveProjectMetadata', - 'MoveProjectRequest', - 'Project', - 'SearchProjectsRequest', - 'SearchProjectsResponse', - 'UndeleteProjectMetadata', - 'UndeleteProjectRequest', - 'UpdateProjectMetadata', - 'UpdateProjectRequest', - 'CreateTagBindingMetadata', - 'CreateTagBindingRequest', - 'DeleteTagBindingMetadata', - 'DeleteTagBindingRequest', - 'ListTagBindingsRequest', - 'ListTagBindingsResponse', - 'TagBinding', - 'CreateTagKeyMetadata', - 'CreateTagKeyRequest', - 'DeleteTagKeyMetadata', - 'DeleteTagKeyRequest', - 'GetTagKeyRequest', - 'ListTagKeysRequest', - 'ListTagKeysResponse', - 'TagKey', - 'UpdateTagKeyMetadata', - 'UpdateTagKeyRequest', - 'CreateTagValueMetadata', - 'CreateTagValueRequest', - 'DeleteTagValueMetadata', - 'DeleteTagValueRequest', - 'GetTagValueRequest', - 'ListTagValuesRequest', - 'ListTagValuesResponse', - 'TagValue', - 'UpdateTagValueMetadata', - 'UpdateTagValueRequest', -) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py deleted file mode 100644 index 9dc4606..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/folders.py +++ /dev/null @@ -1,495 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.resourcemanager.v3', - manifest={ - 'Folder', - 'GetFolderRequest', - 'ListFoldersRequest', - 'ListFoldersResponse', - 'SearchFoldersRequest', - 'SearchFoldersResponse', - 'CreateFolderRequest', - 'CreateFolderMetadata', - 'UpdateFolderRequest', - 'UpdateFolderMetadata', - 'MoveFolderRequest', - 'MoveFolderMetadata', - 'DeleteFolderRequest', - 'DeleteFolderMetadata', - 'UndeleteFolderRequest', - 'UndeleteFolderMetadata', - }, -) - - -class Folder(proto.Message): - r"""A folder in an organization's resource hierarchy, used to - organize that organization's resources. - - Attributes: - name (str): - Output only. The resource name of the folder. Its format is - ``folders/{folder_id}``, for example: "folders/1234". - parent (str): - Required. The folder's parent's resource name. Updates to - the folder's parent must be performed using - [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder]. - display_name (str): - The folder's display name. A folder's display name must be - unique amongst its siblings. For example, no two folders - with the same parent can share the same display name. The - display name must start and end with a letter or digit, may - contain letters, digits, spaces, hyphens and underscores and - can be no longer than 30 characters. This is captured by the - regular expression: - ``[\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?``. - state (google.cloud.resourcemanager_v3.types.Folder.State): - Output only. The lifecycle state of the folder. Updates to - the state must be performed using - [DeleteFolder][google.cloud.resourcemanager.v3.Folders.DeleteFolder] - and - [UndeleteFolder][google.cloud.resourcemanager.v3.Folders.UndeleteFolder]. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when the folder was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when the folder was - last modified. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when the folder was - requested to be deleted. - etag (str): - Output only. A checksum computed by the - server based on the current value of the folder - resource. This may be sent on update and delete - requests to ensure the client has an up-to-date - value before proceeding. - """ - class State(proto.Enum): - r"""Folder lifecycle states. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. - ACTIVE (1): - The normal and active state. - DELETE_REQUESTED (2): - The folder has been marked for deletion by - the user. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - DELETE_REQUESTED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=8, - ) - - -class GetFolderRequest(proto.Message): - r"""The GetFolder request message. - - Attributes: - name (str): - Required. The resource name of the folder to retrieve. Must - be of the form ``folders/{folder_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFoldersRequest(proto.Message): - r"""The ListFolders request message. - - Attributes: - parent (str): - Required. The resource name of the organization or folder - whose folders are being listed. Must be of the form - ``folders/{folder_id}`` or ``organizations/{org_id}``. - Access to this method is controlled by checking the - ``resourcemanager.folders.list`` permission on the - ``parent``. - page_size (int): - Optional. The maximum number of folders to - return in the response. If unspecified, server - picks an appropriate default. - page_token (str): - Optional. A pagination token returned from a previous call - to ``ListFolders`` that indicates where this listing should - continue from. - show_deleted (bool): - Optional. Controls whether folders in the - [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED] - state should be returned. Defaults to false. - """ - - 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, - ) - show_deleted: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListFoldersResponse(proto.Message): - r"""The ListFolders response message. - - Attributes: - folders (MutableSequence[google.cloud.resourcemanager_v3.types.Folder]): - A possibly paginated list of folders that are - direct descendants of the specified parent - resource. - next_page_token (str): - A pagination token returned from a previous call to - ``ListFolders`` that indicates from where listing should - continue. - """ - - @property - def raw_page(self): - return self - - folders: MutableSequence['Folder'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Folder', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchFoldersRequest(proto.Message): - r"""The request message for searching folders. - - Attributes: - page_size (int): - Optional. The maximum number of folders to - return in the response. If unspecified, server - picks an appropriate default. - page_token (str): - Optional. A pagination token returned from a previous call - to ``SearchFolders`` that indicates from where search should - continue. - query (str): - Optional. Search criteria used to select the folders to - return. If no search criteria is specified then all - accessible folders will be returned. - - Query expressions can be used to restrict results based upon - displayName, state and parent, where the operators ``=`` - (``:``) ``NOT``, ``AND`` and ``OR`` can be used along with - the suffix wildcard symbol ``*``. - - The ``displayName`` field in a query expression should use - escaped quotes for values that include whitespace to prevent - unexpected behavior. - - :: - - | Field | Description | - |-------------------------|----------------------------------------| - | displayName | Filters by displayName. | - | parent | Filters by parent (for example: folders/123). | - | state, lifecycleState | Filters by state. | - - Some example queries are: - - - Query ``displayName=Test*`` returns Folder resources - whose display name starts with "Test". - - Query ``state=ACTIVE`` returns Folder resources with - ``state`` set to ``ACTIVE``. - - Query ``parent=folders/123`` returns Folder resources - that have ``folders/123`` as a parent resource. - - Query ``parent=folders/123 AND state=ACTIVE`` returns - active Folder resources that have ``folders/123`` as a - parent resource. - - Query ``displayName=\\"Test String\\"`` returns Folder - resources with display names that include both "Test" and - "String". - """ - - page_size: int = proto.Field( - proto.INT32, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - query: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchFoldersResponse(proto.Message): - r"""The response message for searching folders. - - Attributes: - folders (MutableSequence[google.cloud.resourcemanager_v3.types.Folder]): - A possibly paginated folder search results. - the specified parent resource. - next_page_token (str): - A pagination token returned from a previous call to - ``SearchFolders`` that indicates from where searching should - continue. - """ - - @property - def raw_page(self): - return self - - folders: MutableSequence['Folder'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Folder', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateFolderRequest(proto.Message): - r"""The CreateFolder request message. - - Attributes: - folder (google.cloud.resourcemanager_v3.types.Folder): - Required. The folder being created, only the - display name and parent will be consulted. All - other fields will be ignored. - """ - - folder: 'Folder' = proto.Field( - proto.MESSAGE, - number=2, - message='Folder', - ) - - -class CreateFolderMetadata(proto.Message): - r"""Metadata pertaining to the Folder creation process. - - Attributes: - display_name (str): - The display name of the folder. - parent (str): - The resource name of the folder or - organization we are creating the folder under. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateFolderRequest(proto.Message): - r"""The request sent to the - [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] - method. - - Only the ``display_name`` field can be changed. All other fields - will be ignored. Use the - [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] - method to change the ``parent`` field. - - Attributes: - folder (google.cloud.resourcemanager_v3.types.Folder): - Required. The new definition of the Folder. It must include - the ``name`` field, which cannot be changed. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Fields to be updated. Only the ``display_name`` - can be updated. - """ - - folder: 'Folder' = proto.Field( - proto.MESSAGE, - number=1, - message='Folder', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateFolderMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by UpdateFolder. - - """ - - -class MoveFolderRequest(proto.Message): - r"""The MoveFolder request message. - - Attributes: - name (str): - Required. The resource name of the Folder to move. Must be - of the form folders/{folder_id} - destination_parent (str): - Required. The resource name of the folder or organization - which should be the folder's new parent. Must be of the form - ``folders/{folder_id}`` or ``organizations/{org_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - destination_parent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class MoveFolderMetadata(proto.Message): - r"""Metadata pertaining to the folder move process. - - Attributes: - display_name (str): - The display name of the folder. - source_parent (str): - The resource name of the folder's parent. - destination_parent (str): - The resource name of the folder or - organization to move the folder to. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - source_parent: str = proto.Field( - proto.STRING, - number=2, - ) - destination_parent: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteFolderRequest(proto.Message): - r"""The DeleteFolder request message. - - Attributes: - name (str): - Required. The resource name of the folder to be deleted. - Must be of the form ``folders/{folder_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteFolderMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - ``Operation`` returned by ``DeleteFolder``. - - """ - - -class UndeleteFolderRequest(proto.Message): - r"""The UndeleteFolder request message. - - Attributes: - name (str): - Required. The resource name of the folder to undelete. Must - be of the form ``folders/{folder_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeleteFolderMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - ``Operation`` returned by ``UndeleteFolder``. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py deleted file mode 100644 index e2395b0..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/organizations.py +++ /dev/null @@ -1,254 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.resourcemanager.v3', - manifest={ - 'Organization', - 'GetOrganizationRequest', - 'SearchOrganizationsRequest', - 'SearchOrganizationsResponse', - 'DeleteOrganizationMetadata', - 'UndeleteOrganizationMetadata', - }, -) - - -class Organization(proto.Message): - r"""The root node in the resource hierarchy to which a particular - entity's (a company, for example) resources belong. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The resource name of the organization. This is - the organization's relative path in the API. Its format is - "organizations/[organization_id]". For example, - "organizations/1234". - display_name (str): - Output only. A human-readable string that - refers to the organization in the Google Cloud - Console. This string is set by the server and - cannot be changed. The string will be set to the - primary domain (for example, "google.com") of - the Google Workspace customer that owns the - organization. - directory_customer_id (str): - Immutable. The G Suite / Workspace customer - id used in the Directory API. - - This field is a member of `oneof`_ ``owner``. - state (google.cloud.resourcemanager_v3.types.Organization.State): - Output only. The organization's current - lifecycle state. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when the Organization - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when the Organization - was last modified. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp when the Organization - was requested for deletion. - etag (str): - Output only. A checksum computed by the - server based on the current value of the - Organization resource. This may be sent on - update and delete requests to ensure the client - has an up-to-date value before proceeding. - """ - class State(proto.Enum): - r"""Organization lifecycle states. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. This is only useful for - distinguishing unset values. - ACTIVE (1): - The normal and active state. - DELETE_REQUESTED (2): - The organization has been marked for deletion - by the user. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - DELETE_REQUESTED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - directory_customer_id: str = proto.Field( - proto.STRING, - number=3, - oneof='owner', - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=8, - ) - - -class GetOrganizationRequest(proto.Message): - r"""The request sent to the ``GetOrganization`` method. The ``name`` - field is required. ``organization_id`` is no longer accepted. - - Attributes: - name (str): - Required. The resource name of the Organization to fetch. - This is the organization's relative path in the API, - formatted as "organizations/[organizationId]". For example, - "organizations/1234". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class SearchOrganizationsRequest(proto.Message): - r"""The request sent to the ``SearchOrganizations`` method. - - Attributes: - page_size (int): - Optional. The maximum number of organizations - to return in the response. If unspecified, - server picks an appropriate default. - page_token (str): - Optional. A pagination token returned from a previous call - to ``SearchOrganizations`` that indicates from where listing - should continue. - query (str): - Optional. An optional query string used to filter the - Organizations to return in the response. Query rules are - case-insensitive. - - :: - - | Field | Description | - |------------------|--------------------------------------------| - | directoryCustomerId, owner.directoryCustomerId | Filters by directory - customer id. | - | domain | Filters by domain. | - - Organizations may be queried by ``directoryCustomerId`` or - by ``domain``, where the domain is a G Suite domain, for - example: - - - Query ``directorycustomerid:123456789`` returns - Organization resources with - ``owner.directory_customer_id`` equal to ``123456789``. - - Query ``domain:google.com`` returns Organization - resources corresponding to the domain ``google.com``. - """ - - page_size: int = proto.Field( - proto.INT32, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - query: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SearchOrganizationsResponse(proto.Message): - r"""The response returned from the ``SearchOrganizations`` method. - - Attributes: - organizations (MutableSequence[google.cloud.resourcemanager_v3.types.Organization]): - The list of Organizations that matched the - search query, possibly paginated. - next_page_token (str): - A pagination token to be used to retrieve the - next page of results. If the result is too large - to fit within the page size specified in the - request, this field will be set with a token - that can be used to fetch the next page of - results. If this field is empty, it indicates - that this response contains the last page of - results. - """ - - @property - def raw_page(self): - return self - - organizations: MutableSequence['Organization'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Organization', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteOrganizationMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - operation returned by DeleteOrganization. - - """ - - -class UndeleteOrganizationMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by UndeleteOrganization. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py deleted file mode 100644 index 2e28b9a..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/projects.py +++ /dev/null @@ -1,584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.resourcemanager.v3', - manifest={ - 'Project', - 'GetProjectRequest', - 'ListProjectsRequest', - 'ListProjectsResponse', - 'SearchProjectsRequest', - 'SearchProjectsResponse', - 'CreateProjectRequest', - 'CreateProjectMetadata', - 'UpdateProjectRequest', - 'UpdateProjectMetadata', - 'MoveProjectRequest', - 'MoveProjectMetadata', - 'DeleteProjectRequest', - 'DeleteProjectMetadata', - 'UndeleteProjectRequest', - 'UndeleteProjectMetadata', - }, -) - - -class Project(proto.Message): - r"""A project is a high-level Google Cloud entity. It is a - container for ACLs, APIs, App Engine Apps, VMs, and other Google - Cloud Platform resources. - - Attributes: - name (str): - Output only. The unique resource name of the project. It is - an int64 generated number prefixed by "projects/". - - Example: ``projects/415104041262`` - parent (str): - Optional. A reference to a parent Resource. eg., - ``organizations/123`` or ``folders/876``. - project_id (str): - Immutable. The unique, user-assigned id of the project. It - must be 6 to 30 lowercase ASCII letters, digits, or hyphens. - It must start with a letter. Trailing hyphens are - prohibited. - - Example: ``tokyo-rain-123`` - state (google.cloud.resourcemanager_v3.types.Project.State): - Output only. The project lifecycle state. - display_name (str): - Optional. A user-assigned display name of the project. When - present it must be between 4 to 30 characters. Allowed - characters are: lowercase and uppercase letters, numbers, - hyphen, single-quote, double-quote, space, and exclamation - point. - - Example: ``My Project`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The most recent time this - resource was modified. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this resource - was requested for deletion. - etag (str): - Output only. A checksum computed by the - server based on the current value of the Project - resource. This may be sent on update and delete - requests to ensure the client has an up-to-date - value before proceeding. - labels (MutableMapping[str, str]): - Optional. The labels associated with this project. - - Label keys must be between 1 and 63 characters long and must - conform to the following regular expression: - [a-z]([-a-z0-9]*[a-z0-9])?. - - Label values must be between 0 and 63 characters long and - must conform to the regular expression - ([a-z]([-a-z0-9]*[a-z0-9])?)?. - - No more than 256 labels can be associated with a given - resource. - - Clients should store labels in a representation such as JSON - that does not depend on specific characters being - disallowed. - - Example: ``"myBusinessDimension" : "businessValue"`` - """ - class State(proto.Enum): - r"""Project lifecycle states. - - Values: - STATE_UNSPECIFIED (0): - Unspecified state. This is only used/useful - for distinguishing unset values. - ACTIVE (1): - The normal and active state. - DELETE_REQUESTED (2): - The project has been marked for deletion by the user (by - invoking - [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject]) - or by the system (Google Cloud Platform). This can generally - be reversed by invoking [UndeleteProject] - [google.cloud.resourcemanager.v3.Projects.UndeleteProject]. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - DELETE_REQUESTED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - project_id: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - display_name: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - delete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=9, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -class GetProjectRequest(proto.Message): - r"""The request sent to the - [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] - method. - - Attributes: - name (str): - Required. The name of the project (for example, - ``projects/415104041262``). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProjectsRequest(proto.Message): - r"""The request sent to the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - - Attributes: - parent (str): - Required. The name of the parent resource to - list projects under. - For example, setting this field to - 'folders/1234' would list all projects directly - under that folder. - page_token (str): - Optional. A pagination token returned from a previous call - to [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects] that - indicates from where listing should continue. - page_size (int): - Optional. The maximum number of projects to - return in the response. The server can return - fewer projects than requested. If unspecified, - server picks an appropriate default. - show_deleted (bool): - Optional. Indicate that projects in the ``DELETE_REQUESTED`` - state should also be returned. Normally only ``ACTIVE`` - projects are returned. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - show_deleted: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListProjectsResponse(proto.Message): - r"""A page of the response received from the - [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects] - method. - - A paginated response where more pages are available has - ``next_page_token`` set. This token can be used in a subsequent - request to retrieve the next request page. - - NOTE: A response may contain fewer elements than the request - ``page_size`` and still have a ``next_page_token``. - - Attributes: - projects (MutableSequence[google.cloud.resourcemanager_v3.types.Project]): - The list of Projects under the parent. This - list can be paginated. - next_page_token (str): - Pagination token. - - If the result set is too large to fit in a single response, - this token is returned. It encodes the position of the - current result cursor. Feeding this value into a new list - request with the ``page_token`` parameter gives the next - page of the results. - - When ``next_page_token`` is not filled in, there is no next - page and the list returned is the last page in the result - set. - - Pagination tokens have a limited lifetime. - """ - - @property - def raw_page(self): - return self - - projects: MutableSequence['Project'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Project', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchProjectsRequest(proto.Message): - r"""The request sent to the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - - Attributes: - query (str): - Optional. A query string for searching for projects that the - caller has ``resourcemanager.projects.get`` permission to. - If multiple fields are included in the query, the it will - return results that match any of the fields. Some eligible - fields are: - - :: - - | Field | Description | - |-------------------------|----------------------------------------------| - | displayName, name | Filters by displayName. | - | parent | Project's parent. (for example: folders/123, - organizations/*) Prefer parent field over parent.type and parent.id. | - | parent.type | Parent's type: `folder` or `organization`. | - | parent.id | Parent's id number (for example: 123) | - | id, projectId | Filters by projectId. | - | state, lifecycleState | Filters by state. | - | labels | Filters by label name or value. | - | labels. (where *key* is the name of a label) | Filters by label - name. | - - Search expressions are case insensitive. - - Some examples queries: - - :: - - | Query | Description | - |------------------|-----------------------------------------------------| - | name:how* | The project's name starts with "how". | - | name:Howl | The project's name is `Howl` or `howl`. | - | name:HOWL | Equivalent to above. | - | NAME:howl | Equivalent to above. | - | labels.color:* | The project has the label `color`. | - | labels.color:red | The project's label `color` has the value `red`. | - | labels.color:red labels.size:big | The project's label `color` has - the value `red` and its label `size` has the value `big`. | - - If no query is specified, the call will return projects for - which the user has the ``resourcemanager.projects.get`` - permission. - page_token (str): - Optional. A pagination token returned from a previous call - to [ListProjects] - [google.cloud.resourcemanager.v3.Projects.ListProjects] that - indicates from where listing should continue. - page_size (int): - Optional. The maximum number of projects to - return in the response. The server can return - fewer projects than requested. If unspecified, - server picks an appropriate default. - """ - - query: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class SearchProjectsResponse(proto.Message): - r"""A page of the response received from the - [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects] - method. - - A paginated response where more pages are available has - ``next_page_token`` set. This token can be used in a subsequent - request to retrieve the next request page. - - Attributes: - projects (MutableSequence[google.cloud.resourcemanager_v3.types.Project]): - The list of Projects that matched the list - filter query. This list can be paginated. - next_page_token (str): - Pagination token. - - If the result set is too large to fit in a single response, - this token is returned. It encodes the position of the - current result cursor. Feeding this value into a new list - request with the ``page_token`` parameter gives the next - page of the results. - - When ``next_page_token`` is not filled in, there is no next - page and the list returned is the last page in the result - set. - - Pagination tokens have a limited lifetime. - """ - - @property - def raw_page(self): - return self - - projects: MutableSequence['Project'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Project', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateProjectRequest(proto.Message): - r"""The request sent to the - [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject] - method. - - Attributes: - project (google.cloud.resourcemanager_v3.types.Project): - Required. The Project to create. - - Project ID is required. If the requested ID is unavailable, - the request fails. - - If the ``parent`` field is set, the - ``resourcemanager.projects.create`` permission is checked on - the parent resource. If no parent is set and the - authorization credentials belong to an Organziation, the - parent will be set to that Organization. - """ - - project: 'Project' = proto.Field( - proto.MESSAGE, - number=1, - message='Project', - ) - - -class CreateProjectMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by CreateProject. It provides insight for when - significant phases of Project creation have completed. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Creation time of the project creation - workflow. - gettable (bool): - True if the project can be retrieved using ``GetProject``. - No other operations on the project are guaranteed to work - until the project creation is complete. - ready (bool): - True if the project creation process is - complete. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - gettable: bool = proto.Field( - proto.BOOL, - number=2, - ) - ready: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class UpdateProjectRequest(proto.Message): - r"""The request sent to the - [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject] - method. - - Only the ``display_name`` and ``labels`` fields can be change. Use - the - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method to change the ``parent`` field. - - Attributes: - project (google.cloud.resourcemanager_v3.types.Project): - Required. The new definition of the project. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. An update mask to selectively - update fields. - """ - - project: 'Project' = proto.Field( - proto.MESSAGE, - number=1, - message='Project', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateProjectMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by UpdateProject. - - """ - - -class MoveProjectRequest(proto.Message): - r"""The request sent to - [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject] - method. - - Attributes: - name (str): - Required. The name of the project to move. - destination_parent (str): - Required. The new parent to move the Project - under. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - destination_parent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class MoveProjectMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by MoveProject. - - """ - - -class DeleteProjectRequest(proto.Message): - r"""[DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject] - method. - - Attributes: - name (str): - Required. The name of the Project (for example, - ``projects/415104041262``). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteProjectMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by ``DeleteProject``. - - """ - - -class UndeleteProjectRequest(proto.Message): - r"""The request sent to the [UndeleteProject] - [google.cloud.resourcemanager.v3.Projects.UndeleteProject] method. - - Attributes: - name (str): - Required. The name of the project (for example, - ``projects/415104041262``). - - Required. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeleteProjectMetadata(proto.Message): - r"""A status object which is used as the ``metadata`` field for the - Operation returned by ``UndeleteProject``. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py deleted file mode 100644 index 5b10775..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_bindings.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.resourcemanager.v3', - manifest={ - 'TagBinding', - 'CreateTagBindingMetadata', - 'CreateTagBindingRequest', - 'DeleteTagBindingMetadata', - 'DeleteTagBindingRequest', - 'ListTagBindingsRequest', - 'ListTagBindingsResponse', - }, -) - - -class TagBinding(proto.Message): - r"""A TagBinding represents a connection between a TagValue and a - cloud resource (currently project, folder, or organization). - Once a TagBinding is created, the TagValue is applied to all the - descendants of the cloud resource. - - Attributes: - name (str): - Output only. The name of the TagBinding. This is a String of - the form: - ``tagBindings/{full-resource-name}/{tag-value-name}`` (e.g. - ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). - parent (str): - The full resource name of the resource the TagValue is bound - to. E.g. - ``//cloudresourcemanager.googleapis.com/projects/123`` - tag_value (str): - The TagValue of the TagBinding. Must be of the form - ``tagValues/456``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - tag_value: str = proto.Field( - proto.STRING, - number=3, - ) - - -class CreateTagBindingMetadata(proto.Message): - r"""Runtime operation information for creating a TagValue. - """ - - -class CreateTagBindingRequest(proto.Message): - r"""The request message to create a TagBinding. - - Attributes: - tag_binding (google.cloud.resourcemanager_v3.types.TagBinding): - Required. The TagBinding to be created. - validate_only (bool): - Optional. Set to true to perform the - validations necessary for creating the resource, - but not actually perform the action. - """ - - tag_binding: 'TagBinding' = proto.Field( - proto.MESSAGE, - number=1, - message='TagBinding', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class DeleteTagBindingMetadata(proto.Message): - r"""Runtime operation information for deleting a TagBinding. - """ - - -class DeleteTagBindingRequest(proto.Message): - r"""The request message to delete a TagBinding. - - Attributes: - name (str): - Required. The name of the TagBinding. This is a String of - the form: ``tagBindings/{id}`` (e.g. - ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``). - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListTagBindingsRequest(proto.Message): - r"""The request message to list all TagBindings for a parent. - - Attributes: - parent (str): - Required. The full resource name of a - resource for which you want to list existing - TagBindings. E.g. - "//cloudresourcemanager.googleapis.com/projects/123". - page_size (int): - Optional. The maximum number of TagBindings - to return in the response. The server allows a - maximum of 300 TagBindings to return. If - unspecified, the server will use 100 as the - default. - page_token (str): - Optional. A pagination token returned from a previous call - to ``ListTagBindings`` that indicates where this listing - should continue from. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTagBindingsResponse(proto.Message): - r"""The ListTagBindings response. - - Attributes: - tag_bindings (MutableSequence[google.cloud.resourcemanager_v3.types.TagBinding]): - A possibly paginated list of TagBindings for - the specified TagValue or resource. - next_page_token (str): - Pagination token. - - If the result set is too large to fit in a single response, - this token is returned. It encodes the position of the - current result cursor. Feeding this value into a new list - request with the ``page_token`` parameter gives the next - page of the results. - - When ``next_page_token`` is not filled in, there is no next - page and the list returned is the last page in the result - set. - - Pagination tokens have a limited lifetime. - """ - - @property - def raw_page(self): - return self - - tag_bindings: MutableSequence['TagBinding'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TagBinding', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py deleted file mode 100644 index 4132ed8..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_keys.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.resourcemanager.v3', - manifest={ - 'TagKey', - 'ListTagKeysRequest', - 'ListTagKeysResponse', - 'GetTagKeyRequest', - 'CreateTagKeyRequest', - 'CreateTagKeyMetadata', - 'UpdateTagKeyRequest', - 'UpdateTagKeyMetadata', - 'DeleteTagKeyRequest', - 'DeleteTagKeyMetadata', - }, -) - - -class TagKey(proto.Message): - r"""A TagKey, used to group a set of TagValues. - - Attributes: - name (str): - Immutable. The resource name for a TagKey. Must be in the - format ``tagKeys/{tag_key_id}``, where ``tag_key_id`` is the - generated numeric id for the TagKey. - parent (str): - Immutable. The resource name of the new TagKey's parent. - Must be of the form ``organizations/{org_id}``. - short_name (str): - Required. Immutable. The user friendly name for a TagKey. - The short name should be unique for TagKeys within the same - tag namespace. - - The short name must be 1-63 characters, beginning and ending - with an alphanumeric character ([a-z0-9A-Z]) with dashes - (-), underscores (_), dots (.), and alphanumerics between. - namespaced_name (str): - Output only. Immutable. Namespaced name of - the TagKey. - description (str): - Optional. User-assigned description of the - TagKey. Must not exceed 256 characters. - Read-write. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Update time. - etag (str): - Optional. Entity tag which users can pass to - prevent race conditions. This field is always - set in server responses. See UpdateTagKeyRequest - for details. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - short_name: str = proto.Field( - proto.STRING, - number=3, - ) - namespaced_name: str = proto.Field( - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=8, - ) - - -class ListTagKeysRequest(proto.Message): - r"""The request message for listing all TagKeys under a parent - resource. - - Attributes: - parent (str): - Required. The resource name of the new TagKey's parent. Must - be of the form ``folders/{folder_id}`` or - ``organizations/{org_id}``. - page_size (int): - Optional. The maximum number of TagKeys to - return in the response. The server allows a - maximum of 300 TagKeys to return. If - unspecified, the server will use 100 as the - default. - page_token (str): - Optional. A pagination token returned from a previous call - to ``ListTagKey`` that indicates where this listing should - continue from. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTagKeysResponse(proto.Message): - r"""The ListTagKeys response message. - - Attributes: - tag_keys (MutableSequence[google.cloud.resourcemanager_v3.types.TagKey]): - List of TagKeys that live under the specified - parent in the request. - next_page_token (str): - A pagination token returned from a previous call to - ``ListTagKeys`` that indicates from where listing should - continue. - """ - - @property - def raw_page(self): - return self - - tag_keys: MutableSequence['TagKey'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TagKey', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTagKeyRequest(proto.Message): - r"""The request message for getting a TagKey. - - Attributes: - name (str): - Required. A resource name in the format ``tagKeys/{id}``, - such as ``tagKeys/123``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateTagKeyRequest(proto.Message): - r"""The request message for creating a TagKey. - - Attributes: - tag_key (google.cloud.resourcemanager_v3.types.TagKey): - Required. The TagKey to be created. Only fields - ``short_name``, ``description``, and ``parent`` are - considered during the creation request. - validate_only (bool): - Optional. Set to true to perform validations - necessary for creating the resource, but not - actually perform the action. - """ - - tag_key: 'TagKey' = proto.Field( - proto.MESSAGE, - number=1, - message='TagKey', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class CreateTagKeyMetadata(proto.Message): - r"""Runtime operation information for creating a TagKey. - """ - - -class UpdateTagKeyRequest(proto.Message): - r"""The request message for updating a TagKey. - - Attributes: - tag_key (google.cloud.resourcemanager_v3.types.TagKey): - Required. The new definition of the TagKey. Only the - ``description`` and ``etag`` fields can be updated by this - request. If the ``etag`` field is not empty, it must match - the ``etag`` field of the existing tag key. Otherwise, - ``FAILED_PRECONDITION`` will be returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Fields to be updated. The mask may only contain - ``description`` or ``etag``. If omitted entirely, both - ``description`` and ``etag`` are assumed to be significant. - validate_only (bool): - Set as true to perform validations necessary - for updating the resource, but not actually - perform the action. - """ - - tag_key: 'TagKey' = proto.Field( - proto.MESSAGE, - number=1, - message='TagKey', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class UpdateTagKeyMetadata(proto.Message): - r"""Runtime operation information for updating a TagKey. - """ - - -class DeleteTagKeyRequest(proto.Message): - r"""The request message for deleting a TagKey. - - Attributes: - name (str): - Required. The resource name of a TagKey to be deleted in the - format ``tagKeys/123``. The TagKey cannot be a parent of any - existing TagValues or it will not be deleted successfully. - validate_only (bool): - Optional. Set as true to perform validations - necessary for deletion, but not actually perform - the action. - etag (str): - Optional. The etag known to the client for - the expected state of the TagKey. This is to be - used for optimistic concurrency. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteTagKeyMetadata(proto.Message): - r"""Runtime operation information for deleting a TagKey. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py b/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py deleted file mode 100644 index 0de3665..0000000 --- a/owl-bot-staging/v3/google/cloud/resourcemanager_v3/types/tag_values.py +++ /dev/null @@ -1,304 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.resourcemanager.v3', - manifest={ - 'TagValue', - 'ListTagValuesRequest', - 'ListTagValuesResponse', - 'GetTagValueRequest', - 'CreateTagValueRequest', - 'CreateTagValueMetadata', - 'UpdateTagValueRequest', - 'UpdateTagValueMetadata', - 'DeleteTagValueRequest', - 'DeleteTagValueMetadata', - }, -) - - -class TagValue(proto.Message): - r"""A TagValue is a child of a particular TagKey. This is used to - group cloud resources for the purpose of controlling them using - policies. - - Attributes: - name (str): - Immutable. Resource name for TagValue in the format - ``tagValues/456``. - parent (str): - Immutable. The resource name of the new TagValue's parent - TagKey. Must be of the form ``tagKeys/{tag_key_id}``. - short_name (str): - Required. Immutable. User-assigned short name for TagValue. - The short name should be unique for TagValues within the - same parent TagKey. - - The short name must be 63 characters or less, beginning and - ending with an alphanumeric character ([a-z0-9A-Z]) with - dashes (-), underscores (_), dots (.), and alphanumerics - between. - namespaced_name (str): - Output only. Namespaced name of the TagValue. Must be in the - format - ``{organization_id}/{tag_key_short_name}/{short_name}``. - description (str): - Optional. User-assigned description of the - TagValue. Must not exceed 256 characters. - - Read-write. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Update time. - etag (str): - Optional. Entity tag which users can pass to - prevent race conditions. This field is always - set in server responses. See - UpdateTagValueRequest for details. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - short_name: str = proto.Field( - proto.STRING, - number=3, - ) - namespaced_name: str = proto.Field( - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - etag: str = proto.Field( - proto.STRING, - number=8, - ) - - -class ListTagValuesRequest(proto.Message): - r"""The request message for listing TagValues for the specified - TagKey. - - Attributes: - parent (str): - Required. Resource name for TagKey, parent of the TagValues - to be listed, in the format ``tagKeys/123``. - page_size (int): - Optional. The maximum number of TagValues to - return in the response. The server allows a - maximum of 300 TagValues to return. If - unspecified, the server will use 100 as the - default. - page_token (str): - Optional. A pagination token returned from a previous call - to ``ListTagValues`` that indicates where this listing - should continue from. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListTagValuesResponse(proto.Message): - r"""The ListTagValues response. - - Attributes: - tag_values (MutableSequence[google.cloud.resourcemanager_v3.types.TagValue]): - A possibly paginated list of TagValues that - are direct descendants of the specified parent - TagKey. - next_page_token (str): - A pagination token returned from a previous call to - ``ListTagValues`` that indicates from where listing should - continue. This is currently not used, but the server may at - any point start supplying a valid token. - """ - - @property - def raw_page(self): - return self - - tag_values: MutableSequence['TagValue'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TagValue', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTagValueRequest(proto.Message): - r"""The request message for getting a TagValue. - - Attributes: - name (str): - Required. Resource name for TagValue to be fetched in the - format ``tagValues/456``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateTagValueRequest(proto.Message): - r"""The request message for creating a TagValue. - - Attributes: - tag_value (google.cloud.resourcemanager_v3.types.TagValue): - Required. The TagValue to be created. Only fields - ``short_name``, ``description``, and ``parent`` are - considered during the creation request. - validate_only (bool): - Optional. Set as true to perform the - validations necessary for creating the resource, - but not actually perform the action. - """ - - tag_value: 'TagValue' = proto.Field( - proto.MESSAGE, - number=1, - message='TagValue', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class CreateTagValueMetadata(proto.Message): - r"""Runtime operation information for creating a TagValue. - """ - - -class UpdateTagValueRequest(proto.Message): - r"""The request message for updating a TagValue. - - Attributes: - tag_value (google.cloud.resourcemanager_v3.types.TagValue): - Required. The new definition of the TagValue. Only fields - ``description`` and ``etag`` fields can be updated by this - request. If the ``etag`` field is nonempty, it must match - the ``etag`` field of the existing ControlGroup. Otherwise, - ``FAILED_PRECONDITION`` will be returned. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Fields to be updated. - validate_only (bool): - Optional. True to perform validations - necessary for updating the resource, but not - actually perform the action. - """ - - tag_value: 'TagValue' = proto.Field( - proto.MESSAGE, - number=1, - message='TagValue', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class UpdateTagValueMetadata(proto.Message): - r"""Runtime operation information for updating a TagValue. - """ - - -class DeleteTagValueRequest(proto.Message): - r"""The request message for deleting a TagValue. - - Attributes: - name (str): - Required. Resource name for TagValue to be - deleted in the format tagValues/456. - validate_only (bool): - Optional. Set as true to perform the - validations necessary for deletion, but not - actually perform the action. - etag (str): - Optional. The etag known to the client for - the expected state of the TagValue. This is to - be used for optimistic concurrency. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - etag: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteTagValueMetadata(proto.Message): - r"""Runtime operation information for deleting a TagValue. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/mypy.ini b/owl-bot-staging/v3/mypy.ini deleted file mode 100644 index 574c5ae..0000000 --- a/owl-bot-staging/v3/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v3/noxfile.py b/owl-bot-staging/v3/noxfile.py deleted file mode 100644 index 97e57dc..0000000 --- a/owl-bot-staging/v3/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/resourcemanager_v3/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py deleted file mode 100644 index d89b2c1..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_CreateFolder_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_create_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.CreateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.create_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_CreateFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py deleted file mode 100644 index 5471a49..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_create_folder_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_CreateFolder_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_create_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.CreateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.create_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_CreateFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py deleted file mode 100644 index a07851a..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_DeleteFolder_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_delete_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_DeleteFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py deleted file mode 100644 index 91b70c7..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_DeleteFolder_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_delete_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_DeleteFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py deleted file mode 100644 index bfa1fc5..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_GetFolder_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_get_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetFolderRequest( - name="name_value", - ) - - # Make the request - response = await client.get_folder(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_GetFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py deleted file mode 100644 index 53416ab..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_folder_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_GetFolder_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_get_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetFolderRequest( - name="name_value", - ) - - # Make the request - response = client.get_folder(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_GetFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py deleted file mode 100644 index 66c59cd..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py deleted file mode 100644 index fcb3417..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py deleted file mode 100644 index 11d2f3f..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListFolders -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_ListFolders_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_list_folders(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListFoldersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_folders(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_ListFolders_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py deleted file mode 100644 index cba1515..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_list_folders_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListFolders -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_ListFolders_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_list_folders(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListFoldersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_folders(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_ListFolders_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py deleted file mode 100644 index b843ac9..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MoveFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_MoveFolder_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_move_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveFolderRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_MoveFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py deleted file mode 100644 index ad3d694..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_move_folder_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MoveFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_MoveFolder_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_move_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveFolderRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_MoveFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py deleted file mode 100644 index 36818e0..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchFolders -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_SearchFolders_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_search_folders(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchFoldersRequest( - ) - - # Make the request - page_result = client.search_folders(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_SearchFolders_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py deleted file mode 100644 index b93aba1..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_search_folders_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchFolders -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_SearchFolders_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_search_folders(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchFoldersRequest( - ) - - # Make the request - page_result = client.search_folders(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_SearchFolders_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py deleted file mode 100644 index d684510..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py deleted file mode 100644 index 5aba5b5..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py deleted file mode 100644 index 2c8ca84..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py deleted file mode 100644 index 1fde48a..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py deleted file mode 100644 index abc8ad3..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_UndeleteFolder_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_undelete_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_UndeleteFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py deleted file mode 100644 index 6977800..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_UndeleteFolder_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_undelete_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteFolderRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_UndeleteFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py deleted file mode 100644 index 515f4ae..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_UpdateFolder_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_update_folder(): - # Create a client - client = resourcemanager_v3.FoldersAsyncClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.UpdateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.update_folder(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_UpdateFolder_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py deleted file mode 100644 index c2b5f39..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFolder -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Folders_UpdateFolder_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_update_folder(): - # Create a client - client = resourcemanager_v3.FoldersClient() - - # Initialize request argument(s) - folder = resourcemanager_v3.Folder() - folder.parent = "parent_value" - - request = resourcemanager_v3.UpdateFolderRequest( - folder=folder, - ) - - # Make the request - operation = client.update_folder(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Folders_UpdateFolder_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py deleted file mode 100644 index a6fff7f..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py deleted file mode 100644 index 423b614..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py deleted file mode 100644 index 55de2b6..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOrganization -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_GetOrganization_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_get_organization(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetOrganizationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_organization(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_GetOrganization_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py deleted file mode 100644 index aff37ad..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_get_organization_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOrganization -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_GetOrganization_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_get_organization(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetOrganizationRequest( - name="name_value", - ) - - # Make the request - response = client.get_organization(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_GetOrganization_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py deleted file mode 100644 index 45db889..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchOrganizations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_search_organizations(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchOrganizationsRequest( - ) - - # Make the request - page_result = client.search_organizations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py deleted file mode 100644 index 2481a0f..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchOrganizations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_search_organizations(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchOrganizationsRequest( - ) - - # Make the request - page_result = client.search_organizations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py deleted file mode 100644 index 650e62a..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py deleted file mode 100644 index 79c73a8..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py deleted file mode 100644 index 423d181..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.OrganizationsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py deleted file mode 100644 index c0f6aa1..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.OrganizationsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py deleted file mode 100644 index 0a6c6b8..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_CreateProject_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_create_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateProjectRequest( - ) - - # Make the request - operation = client.create_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_CreateProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py deleted file mode 100644 index ccb70b8..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_create_project_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_CreateProject_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_create_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateProjectRequest( - ) - - # Make the request - operation = client.create_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_CreateProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py deleted file mode 100644 index dc6bb6c..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_DeleteProject_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_delete_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_DeleteProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py deleted file mode 100644 index fe6641a..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_delete_project_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_DeleteProject_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_delete_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_DeleteProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py deleted file mode 100644 index 8f0a502..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py deleted file mode 100644 index 67b2186..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py deleted file mode 100644 index bc2885e..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_GetProject_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_get_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetProjectRequest( - name="name_value", - ) - - # Make the request - response = await client.get_project(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_GetProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py deleted file mode 100644 index 4d5dc0b..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_get_project_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_GetProject_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_get_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetProjectRequest( - name="name_value", - ) - - # Make the request - response = client.get_project(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_GetProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py deleted file mode 100644 index 91c495f..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProjects -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_ListProjects_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_list_projects(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListProjectsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_projects(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_ListProjects_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py deleted file mode 100644 index 09d9898..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_list_projects_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListProjects -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_ListProjects_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_list_projects(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListProjectsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_projects(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_ListProjects_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py deleted file mode 100644 index ecdd64e..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MoveProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_MoveProject_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_move_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveProjectRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_MoveProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py deleted file mode 100644 index 37cc2cd..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_move_project_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MoveProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_MoveProject_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_move_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.MoveProjectRequest( - name="name_value", - destination_parent="destination_parent_value", - ) - - # Make the request - operation = client.move_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_MoveProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py deleted file mode 100644 index faa6502..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchProjects -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_SearchProjects_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_search_projects(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchProjectsRequest( - ) - - # Make the request - page_result = client.search_projects(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_SearchProjects_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py deleted file mode 100644 index a870908..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_search_projects_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchProjects -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_SearchProjects_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_search_projects(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.SearchProjectsRequest( - ) - - # Make the request - page_result = client.search_projects(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_SearchProjects_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py deleted file mode 100644 index d48466b..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py deleted file mode 100644 index 4ca4a00..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py deleted file mode 100644 index e0261b7..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py deleted file mode 100644 index 96d142d..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py deleted file mode 100644 index c818309..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_UndeleteProject_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_undelete_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_UndeleteProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py deleted file mode 100644 index 2961e89..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_undelete_project_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_UndeleteProject_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_undelete_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UndeleteProjectRequest( - name="name_value", - ) - - # Make the request - operation = client.undelete_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_UndeleteProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py deleted file mode 100644 index cd9022e..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_UpdateProject_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_update_project(): - # Create a client - client = resourcemanager_v3.ProjectsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UpdateProjectRequest( - ) - - # Make the request - operation = client.update_project(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_UpdateProject_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py deleted file mode 100644 index 1e19ce8..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_projects_update_project_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateProject -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_Projects_UpdateProject_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_update_project(): - # Create a client - client = resourcemanager_v3.ProjectsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.UpdateProjectRequest( - ) - - # Make the request - operation = client.update_project(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_Projects_UpdateProject_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py deleted file mode 100644 index 18b7eb5..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTagBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_create_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateTagBindingRequest( - ) - - # Make the request - operation = client.create_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py deleted file mode 100644 index 764063f..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTagBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_create_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.CreateTagBindingRequest( - ) - - # Make the request - operation = client.create_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py deleted file mode 100644 index a05a128..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTagBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_delete_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py deleted file mode 100644 index 2ae22e1..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTagBinding -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_delete_tag_binding(): - # Create a client - client = resourcemanager_v3.TagBindingsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagBindingRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_binding(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py deleted file mode 100644 index cf2ed15..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTagBindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_list_tag_bindings(): - # Create a client - client = resourcemanager_v3.TagBindingsAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_bindings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py deleted file mode 100644 index 0b4a750..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTagBindings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_list_tag_bindings(): - # Create a client - client = resourcemanager_v3.TagBindingsClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagBindingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_bindings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py deleted file mode 100644 index 780cbed..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_create_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.create_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py deleted file mode 100644 index ae9a49b..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_create_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.create_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py deleted file mode 100644 index 7143771..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_delete_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagKeyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py deleted file mode 100644 index 3bea763..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_delete_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagKeyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py deleted file mode 100644 index aeb6206..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py deleted file mode 100644 index 7cbb915..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py deleted file mode 100644 index 8121728..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_get_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagKeyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tag_key(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py deleted file mode 100644 index 3228ea3..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_get_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagKeyRequest( - name="name_value", - ) - - # Make the request - response = client.get_tag_key(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py deleted file mode 100644 index 922511e..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTagKeys -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_list_tag_keys(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_keys(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py deleted file mode 100644 index 6ee7f60..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTagKeys -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_list_tag_keys(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_keys(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py deleted file mode 100644 index bd2f51c..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py deleted file mode 100644 index 9d9e820..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py deleted file mode 100644 index 12ace3e..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py deleted file mode 100644 index a317572..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py deleted file mode 100644 index 0eb21f1..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_update_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysAsyncClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.update_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py deleted file mode 100644 index b8f05c9..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTagKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_update_tag_key(): - # Create a client - client = resourcemanager_v3.TagKeysClient() - - # Initialize request argument(s) - tag_key = resourcemanager_v3.TagKey() - tag_key.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagKeyRequest( - tag_key=tag_key, - ) - - # Make the request - operation = client.update_tag_key(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py deleted file mode 100644 index 646f938..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_CreateTagValue_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_create_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.create_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_CreateTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py deleted file mode 100644 index 2ca20b7..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_CreateTagValue_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_create_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.CreateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.create_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_CreateTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py deleted file mode 100644 index 2f9b8ad..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_delete_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagValueRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py deleted file mode 100644 index e7f6a23..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_delete_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = resourcemanager_v3.DeleteTagValueRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py deleted file mode 100644 index 1f05b73..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py deleted file mode 100644 index 0a345a3..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py deleted file mode 100644 index 473529c..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_GetTagValue_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_get_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagValueRequest( - name="name_value", - ) - - # Make the request - response = await client.get_tag_value(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_GetTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py deleted file mode 100644 index 67eabb2..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_GetTagValue_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_get_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = resourcemanager_v3.GetTagValueRequest( - name="name_value", - ) - - # Make the request - response = client.get_tag_value(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_GetTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py deleted file mode 100644 index 2436e0b..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTagValues -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_ListTagValues_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_list_tag_values(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagValuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_values(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_ListTagValues_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py deleted file mode 100644 index 0af2907..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListTagValues -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_ListTagValues_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_list_tag_values(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = resourcemanager_v3.ListTagValuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tag_values(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_ListTagValues_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py deleted file mode 100644 index 385ccfe..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py deleted file mode 100644 index 77abd02..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py deleted file mode 100644 index 67e7083..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py deleted file mode 100644 index 509c9b6..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py deleted file mode 100644 index d75bcf2..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -async def sample_update_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesAsyncClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.update_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_async] diff --git a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py b/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py deleted file mode 100644 index b04b40a..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateTagValue -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-resource-manager - - -# [START cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import resourcemanager_v3 - - -def sample_update_tag_value(): - # Create a client - client = resourcemanager_v3.TagValuesClient() - - # Initialize request argument(s) - tag_value = resourcemanager_v3.TagValue() - tag_value.short_name = "short_name_value" - - request = resourcemanager_v3.UpdateTagValueRequest( - tag_value=tag_value, - ) - - # Make the request - operation = client.update_tag_value(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync] diff --git a/owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json b/owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json deleted file mode 100644 index bd24c8e..0000000 --- a/owl-bot-staging/v3/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json +++ /dev/null @@ -1,7509 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.resourcemanager.v3", - "version": "v3" - } - ], - "language": "PYTHON", - "name": "google-cloud-resource-manager", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.create_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.CreateFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "CreateFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateFolderRequest" - }, - { - "name": "folder", - "type": "google.cloud.resourcemanager_v3.types.Folder" - }, - { - "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_folder" - }, - "description": "Sample for CreateFolder", - "file": "cloudresourcemanager_v3_generated_folders_create_folder_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_CreateFolder_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_create_folder_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.create_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.CreateFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "CreateFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateFolderRequest" - }, - { - "name": "folder", - "type": "google.cloud.resourcemanager_v3.types.Folder" - }, - { - "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_folder" - }, - "description": "Sample for CreateFolder", - "file": "cloudresourcemanager_v3_generated_folders_create_folder_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_CreateFolder_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_create_folder_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.delete_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.DeleteFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "DeleteFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteFolderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_folder" - }, - "description": "Sample for DeleteFolder", - "file": "cloudresourcemanager_v3_generated_folders_delete_folder_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_DeleteFolder_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_delete_folder_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.delete_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.DeleteFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "DeleteFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteFolderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_folder" - }, - "description": "Sample for DeleteFolder", - "file": "cloudresourcemanager_v3_generated_folders_delete_folder_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_DeleteFolder_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_delete_folder_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.get_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.GetFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "GetFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetFolderRequest" - }, - { - "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.resourcemanager_v3.types.Folder", - "shortName": "get_folder" - }, - "description": "Sample for GetFolder", - "file": "cloudresourcemanager_v3_generated_folders_get_folder_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_GetFolder_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": "cloudresourcemanager_v3_generated_folders_get_folder_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.get_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.GetFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "GetFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetFolderRequest" - }, - { - "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.resourcemanager_v3.types.Folder", - "shortName": "get_folder" - }, - "description": "Sample for GetFolder", - "file": "cloudresourcemanager_v3_generated_folders_get_folder_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_GetFolder_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": "cloudresourcemanager_v3_generated_folders_get_folder_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.list_folders", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.ListFolders", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "ListFolders" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListFoldersRequest" - }, - { - "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.resourcemanager_v3.services.folders.pagers.ListFoldersAsyncPager", - "shortName": "list_folders" - }, - "description": "Sample for ListFolders", - "file": "cloudresourcemanager_v3_generated_folders_list_folders_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_ListFolders_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": "cloudresourcemanager_v3_generated_folders_list_folders_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.list_folders", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.ListFolders", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "ListFolders" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListFoldersRequest" - }, - { - "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.resourcemanager_v3.services.folders.pagers.ListFoldersPager", - "shortName": "list_folders" - }, - "description": "Sample for ListFolders", - "file": "cloudresourcemanager_v3_generated_folders_list_folders_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_ListFolders_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": "cloudresourcemanager_v3_generated_folders_list_folders_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.move_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.MoveFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "MoveFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.MoveFolderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "destination_parent", - "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": "move_folder" - }, - "description": "Sample for MoveFolder", - "file": "cloudresourcemanager_v3_generated_folders_move_folder_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_MoveFolder_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_move_folder_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.move_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.MoveFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "MoveFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.MoveFolderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "destination_parent", - "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": "move_folder" - }, - "description": "Sample for MoveFolder", - "file": "cloudresourcemanager_v3_generated_folders_move_folder_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_MoveFolder_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_move_folder_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.search_folders", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.SearchFolders", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "SearchFolders" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.SearchFoldersRequest" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersAsyncPager", - "shortName": "search_folders" - }, - "description": "Sample for SearchFolders", - "file": "cloudresourcemanager_v3_generated_folders_search_folders_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_SearchFolders_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_search_folders_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.search_folders", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.SearchFolders", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "SearchFolders" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.SearchFoldersRequest" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.resourcemanager_v3.services.folders.pagers.SearchFoldersPager", - "shortName": "search_folders" - }, - "description": "Sample for SearchFolders", - "file": "cloudresourcemanager_v3_generated_folders_search_folders_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_SearchFolders_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_search_folders_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.undelete_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.UndeleteFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "UndeleteFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UndeleteFolderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "undelete_folder" - }, - "description": "Sample for UndeleteFolder", - "file": "cloudresourcemanager_v3_generated_folders_undelete_folder_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_UndeleteFolder_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_undelete_folder_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.undelete_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.UndeleteFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "UndeleteFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UndeleteFolderRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "undelete_folder" - }, - "description": "Sample for UndeleteFolder", - "file": "cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_UndeleteFolder_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_undelete_folder_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient", - "shortName": "FoldersAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersAsyncClient.update_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.UpdateFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "UpdateFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateFolderRequest" - }, - { - "name": "folder", - "type": "google.cloud.resourcemanager_v3.types.Folder" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_folder" - }, - "description": "Sample for UpdateFolder", - "file": "cloudresourcemanager_v3_generated_folders_update_folder_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_UpdateFolder_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_update_folder_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.FoldersClient", - "shortName": "FoldersClient" - }, - "fullName": "google.cloud.resourcemanager_v3.FoldersClient.update_folder", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Folders.UpdateFolder", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Folders", - "shortName": "Folders" - }, - "shortName": "UpdateFolder" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateFolderRequest" - }, - { - "name": "folder", - "type": "google.cloud.resourcemanager_v3.types.Folder" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_folder" - }, - "description": "Sample for UpdateFolder", - "file": "cloudresourcemanager_v3_generated_folders_update_folder_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Folders_UpdateFolder_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_folders_update_folder_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", - "shortName": "OrganizationsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", - "shortName": "OrganizationsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", - "shortName": "OrganizationsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.get_organization", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.GetOrganization", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "GetOrganization" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetOrganizationRequest" - }, - { - "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.resourcemanager_v3.types.Organization", - "shortName": "get_organization" - }, - "description": "Sample for GetOrganization", - "file": "cloudresourcemanager_v3_generated_organizations_get_organization_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetOrganization_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": "cloudresourcemanager_v3_generated_organizations_get_organization_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", - "shortName": "OrganizationsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.get_organization", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.GetOrganization", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "GetOrganization" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetOrganizationRequest" - }, - { - "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.resourcemanager_v3.types.Organization", - "shortName": "get_organization" - }, - "description": "Sample for GetOrganization", - "file": "cloudresourcemanager_v3_generated_organizations_get_organization_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_GetOrganization_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": "cloudresourcemanager_v3_generated_organizations_get_organization_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", - "shortName": "OrganizationsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.search_organizations", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.SearchOrganizations", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "SearchOrganizations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsAsyncPager", - "shortName": "search_organizations" - }, - "description": "Sample for SearchOrganizations", - "file": "cloudresourcemanager_v3_generated_organizations_search_organizations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_search_organizations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", - "shortName": "OrganizationsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.search_organizations", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.SearchOrganizations", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "SearchOrganizations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsPager", - "shortName": "search_organizations" - }, - "description": "Sample for SearchOrganizations", - "file": "cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_SearchOrganizations_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_search_organizations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", - "shortName": "OrganizationsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", - "shortName": "OrganizationsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient", - "shortName": "OrganizationsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient", - "shortName": "OrganizationsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.OrganizationsClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Organizations.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Organizations", - "shortName": "Organizations" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Organizations_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_organizations_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.create_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.CreateProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "CreateProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateProjectRequest" - }, - { - "name": "project", - "type": "google.cloud.resourcemanager_v3.types.Project" - }, - { - "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_project" - }, - "description": "Sample for CreateProject", - "file": "cloudresourcemanager_v3_generated_projects_create_project_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_CreateProject_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_create_project_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.create_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.CreateProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "CreateProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateProjectRequest" - }, - { - "name": "project", - "type": "google.cloud.resourcemanager_v3.types.Project" - }, - { - "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_project" - }, - "description": "Sample for CreateProject", - "file": "cloudresourcemanager_v3_generated_projects_create_project_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_CreateProject_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_create_project_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.delete_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.DeleteProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "DeleteProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteProjectRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_project" - }, - "description": "Sample for DeleteProject", - "file": "cloudresourcemanager_v3_generated_projects_delete_project_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_DeleteProject_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_delete_project_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.delete_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.DeleteProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "DeleteProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteProjectRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_project" - }, - "description": "Sample for DeleteProject", - "file": "cloudresourcemanager_v3_generated_projects_delete_project_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_DeleteProject_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_delete_project_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.get_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.GetProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "GetProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetProjectRequest" - }, - { - "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.resourcemanager_v3.types.Project", - "shortName": "get_project" - }, - "description": "Sample for GetProject", - "file": "cloudresourcemanager_v3_generated_projects_get_project_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_GetProject_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": "cloudresourcemanager_v3_generated_projects_get_project_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.get_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.GetProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "GetProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetProjectRequest" - }, - { - "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.resourcemanager_v3.types.Project", - "shortName": "get_project" - }, - "description": "Sample for GetProject", - "file": "cloudresourcemanager_v3_generated_projects_get_project_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_GetProject_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": "cloudresourcemanager_v3_generated_projects_get_project_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.list_projects", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.ListProjects", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "ListProjects" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListProjectsRequest" - }, - { - "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.resourcemanager_v3.services.projects.pagers.ListProjectsAsyncPager", - "shortName": "list_projects" - }, - "description": "Sample for ListProjects", - "file": "cloudresourcemanager_v3_generated_projects_list_projects_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_ListProjects_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": "cloudresourcemanager_v3_generated_projects_list_projects_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.list_projects", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.ListProjects", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "ListProjects" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListProjectsRequest" - }, - { - "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.resourcemanager_v3.services.projects.pagers.ListProjectsPager", - "shortName": "list_projects" - }, - "description": "Sample for ListProjects", - "file": "cloudresourcemanager_v3_generated_projects_list_projects_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_ListProjects_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": "cloudresourcemanager_v3_generated_projects_list_projects_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.move_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.MoveProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "MoveProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.MoveProjectRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "destination_parent", - "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": "move_project" - }, - "description": "Sample for MoveProject", - "file": "cloudresourcemanager_v3_generated_projects_move_project_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_MoveProject_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_move_project_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.move_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.MoveProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "MoveProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.MoveProjectRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "destination_parent", - "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": "move_project" - }, - "description": "Sample for MoveProject", - "file": "cloudresourcemanager_v3_generated_projects_move_project_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_MoveProject_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_move_project_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.search_projects", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.SearchProjects", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "SearchProjects" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.SearchProjectsRequest" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsAsyncPager", - "shortName": "search_projects" - }, - "description": "Sample for SearchProjects", - "file": "cloudresourcemanager_v3_generated_projects_search_projects_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_SearchProjects_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_search_projects_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.search_projects", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.SearchProjects", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "SearchProjects" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.SearchProjectsRequest" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsPager", - "shortName": "search_projects" - }, - "description": "Sample for SearchProjects", - "file": "cloudresourcemanager_v3_generated_projects_search_projects_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_SearchProjects_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_search_projects_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.undelete_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.UndeleteProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "UndeleteProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UndeleteProjectRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "undelete_project" - }, - "description": "Sample for UndeleteProject", - "file": "cloudresourcemanager_v3_generated_projects_undelete_project_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_UndeleteProject_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_undelete_project_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.undelete_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.UndeleteProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "UndeleteProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UndeleteProjectRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "undelete_project" - }, - "description": "Sample for UndeleteProject", - "file": "cloudresourcemanager_v3_generated_projects_undelete_project_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_UndeleteProject_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_undelete_project_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient", - "shortName": "ProjectsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsAsyncClient.update_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.UpdateProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "UpdateProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateProjectRequest" - }, - { - "name": "project", - "type": "google.cloud.resourcemanager_v3.types.Project" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_project" - }, - "description": "Sample for UpdateProject", - "file": "cloudresourcemanager_v3_generated_projects_update_project_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_UpdateProject_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_update_project_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient", - "shortName": "ProjectsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.ProjectsClient.update_project", - "method": { - "fullName": "google.cloud.resourcemanager.v3.Projects.UpdateProject", - "service": { - "fullName": "google.cloud.resourcemanager.v3.Projects", - "shortName": "Projects" - }, - "shortName": "UpdateProject" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateProjectRequest" - }, - { - "name": "project", - "type": "google.cloud.resourcemanager_v3.types.Project" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_project" - }, - "description": "Sample for UpdateProject", - "file": "cloudresourcemanager_v3_generated_projects_update_project_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_Projects_UpdateProject_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_projects_update_project_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient", - "shortName": "TagBindingsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient.create_tag_binding", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings.CreateTagBinding", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings", - "shortName": "TagBindings" - }, - "shortName": "CreateTagBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateTagBindingRequest" - }, - { - "name": "tag_binding", - "type": "google.cloud.resourcemanager_v3.types.TagBinding" - }, - { - "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_tag_binding" - }, - "description": "Sample for CreateTagBinding", - "file": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient", - "shortName": "TagBindingsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient.create_tag_binding", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings.CreateTagBinding", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings", - "shortName": "TagBindings" - }, - "shortName": "CreateTagBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateTagBindingRequest" - }, - { - "name": "tag_binding", - "type": "google.cloud.resourcemanager_v3.types.TagBinding" - }, - { - "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_tag_binding" - }, - "description": "Sample for CreateTagBinding", - "file": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagBindings_CreateTagBinding_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_bindings_create_tag_binding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient", - "shortName": "TagBindingsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient.delete_tag_binding", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings.DeleteTagBinding", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings", - "shortName": "TagBindings" - }, - "shortName": "DeleteTagBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_tag_binding" - }, - "description": "Sample for DeleteTagBinding", - "file": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient", - "shortName": "TagBindingsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient.delete_tag_binding", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings.DeleteTagBinding", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings", - "shortName": "TagBindings" - }, - "shortName": "DeleteTagBinding" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_tag_binding" - }, - "description": "Sample for DeleteTagBinding", - "file": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagBindings_DeleteTagBinding_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_bindings_delete_tag_binding_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient", - "shortName": "TagBindingsAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagBindingsAsyncClient.list_tag_bindings", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings.ListTagBindings", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings", - "shortName": "TagBindings" - }, - "shortName": "ListTagBindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListTagBindingsRequest" - }, - { - "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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsAsyncPager", - "shortName": "list_tag_bindings" - }, - "description": "Sample for ListTagBindings", - "file": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_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": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient", - "shortName": "TagBindingsClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagBindingsClient.list_tag_bindings", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings.ListTagBindings", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagBindings", - "shortName": "TagBindings" - }, - "shortName": "ListTagBindings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListTagBindingsRequest" - }, - { - "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.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsPager", - "shortName": "list_tag_bindings" - }, - "description": "Sample for ListTagBindings", - "file": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagBindings_ListTagBindings_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": "cloudresourcemanager_v3_generated_tag_bindings_list_tag_bindings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.create_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.CreateTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "CreateTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateTagKeyRequest" - }, - { - "name": "tag_key", - "type": "google.cloud.resourcemanager_v3.types.TagKey" - }, - { - "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_tag_key" - }, - "description": "Sample for CreateTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.create_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.CreateTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "CreateTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateTagKeyRequest" - }, - { - "name": "tag_key", - "type": "google.cloud.resourcemanager_v3.types.TagKey" - }, - { - "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_tag_key" - }, - "description": "Sample for CreateTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_CreateTagKey_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_create_tag_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.delete_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.DeleteTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "DeleteTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_tag_key" - }, - "description": "Sample for DeleteTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.delete_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.DeleteTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "DeleteTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_tag_key" - }, - "description": "Sample for DeleteTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_DeleteTagKey_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_delete_tag_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.get_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "GetTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetTagKeyRequest" - }, - { - "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.resourcemanager_v3.types.TagKey", - "shortName": "get_tag_key" - }, - "description": "Sample for GetTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetTagKey_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": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.get_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.GetTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "GetTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetTagKeyRequest" - }, - { - "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.resourcemanager_v3.types.TagKey", - "shortName": "get_tag_key" - }, - "description": "Sample for GetTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_GetTagKey_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": "cloudresourcemanager_v3_generated_tag_keys_get_tag_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.list_tag_keys", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.ListTagKeys", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "ListTagKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListTagKeysRequest" - }, - { - "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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysAsyncPager", - "shortName": "list_tag_keys" - }, - "description": "Sample for ListTagKeys", - "file": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_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": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.list_tag_keys", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.ListTagKeys", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "ListTagKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListTagKeysRequest" - }, - { - "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.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysPager", - "shortName": "list_tag_keys" - }, - "description": "Sample for ListTagKeys", - "file": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_ListTagKeys_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": "cloudresourcemanager_v3_generated_tag_keys_list_tag_keys_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient", - "shortName": "TagKeysAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysAsyncClient.update_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.UpdateTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "UpdateTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest" - }, - { - "name": "tag_key", - "type": "google.cloud.resourcemanager_v3.types.TagKey" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_tag_key" - }, - "description": "Sample for UpdateTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient", - "shortName": "TagKeysClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagKeysClient.update_tag_key", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys.UpdateTagKey", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagKeys", - "shortName": "TagKeys" - }, - "shortName": "UpdateTagKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest" - }, - { - "name": "tag_key", - "type": "google.cloud.resourcemanager_v3.types.TagKey" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_tag_key" - }, - "description": "Sample for UpdateTagKey", - "file": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagKeys_UpdateTagKey_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_keys_update_tag_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.create_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.CreateTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "CreateTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateTagValueRequest" - }, - { - "name": "tag_value", - "type": "google.cloud.resourcemanager_v3.types.TagValue" - }, - { - "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_tag_value" - }, - "description": "Sample for CreateTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_CreateTagValue_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.create_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.CreateTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "CreateTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.CreateTagValueRequest" - }, - { - "name": "tag_value", - "type": "google.cloud.resourcemanager_v3.types.TagValue" - }, - { - "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_tag_value" - }, - "description": "Sample for CreateTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_CreateTagValue_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_create_tag_value_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.delete_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.DeleteTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "DeleteTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteTagValueRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_tag_value" - }, - "description": "Sample for DeleteTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.delete_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.DeleteTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "DeleteTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.DeleteTagValueRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_tag_value" - }, - "description": "Sample for DeleteTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_DeleteTagValue_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_delete_tag_value_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.get_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.GetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.get_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.GetTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "GetTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetTagValueRequest" - }, - { - "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.resourcemanager_v3.types.TagValue", - "shortName": "get_tag_value" - }, - "description": "Sample for GetTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetTagValue_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": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.get_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.GetTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "GetTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.GetTagValueRequest" - }, - { - "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.resourcemanager_v3.types.TagValue", - "shortName": "get_tag_value" - }, - "description": "Sample for GetTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_GetTagValue_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": "cloudresourcemanager_v3_generated_tag_values_get_tag_value_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.list_tag_values", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.ListTagValues", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "ListTagValues" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListTagValuesRequest" - }, - { - "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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesAsyncPager", - "shortName": "list_tag_values" - }, - "description": "Sample for ListTagValues", - "file": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_ListTagValues_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": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.list_tag_values", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.ListTagValues", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "ListTagValues" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.ListTagValuesRequest" - }, - { - "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.resourcemanager_v3.services.tag_values.pagers.ListTagValuesPager", - "shortName": "list_tag_values" - }, - "description": "Sample for ListTagValues", - "file": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_ListTagValues_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": "cloudresourcemanager_v3_generated_tag_values_list_tag_values_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.set_iam_policy", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.SetIamPolicy", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.TestIamPermissions", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient", - "shortName": "TagValuesAsyncClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesAsyncClient.update_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.UpdateTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "UpdateTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateTagValueRequest" - }, - { - "name": "tag_value", - "type": "google.cloud.resourcemanager_v3.types.TagValue" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_tag_value" - }, - "description": "Sample for UpdateTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient", - "shortName": "TagValuesClient" - }, - "fullName": "google.cloud.resourcemanager_v3.TagValuesClient.update_tag_value", - "method": { - "fullName": "google.cloud.resourcemanager.v3.TagValues.UpdateTagValue", - "service": { - "fullName": "google.cloud.resourcemanager.v3.TagValues", - "shortName": "TagValues" - }, - "shortName": "UpdateTagValue" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.resourcemanager_v3.types.UpdateTagValueRequest" - }, - { - "name": "tag_value", - "type": "google.cloud.resourcemanager_v3.types.TagValue" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_tag_value" - }, - "description": "Sample for UpdateTagValue", - "file": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudresourcemanager_v3_generated_tag_values_update_tag_value_sync.py" - } - ] -} diff --git a/owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py b/owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py deleted file mode 100644 index da70aa8..0000000 --- a/owl-bot-staging/v3/scripts/fixup_resourcemanager_v3_keywords.py +++ /dev/null @@ -1,209 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class resourcemanagerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_folder': ('folder', ), - 'create_project': ('project', ), - 'create_tag_binding': ('tag_binding', 'validate_only', ), - 'create_tag_key': ('tag_key', 'validate_only', ), - 'create_tag_value': ('tag_value', 'validate_only', ), - 'delete_folder': ('name', ), - 'delete_project': ('name', ), - 'delete_tag_binding': ('name', ), - 'delete_tag_key': ('name', 'validate_only', 'etag', ), - 'delete_tag_value': ('name', 'validate_only', 'etag', ), - 'get_folder': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_organization': ('name', ), - 'get_project': ('name', ), - 'get_tag_key': ('name', ), - 'get_tag_value': ('name', ), - 'list_folders': ('parent', 'page_size', 'page_token', 'show_deleted', ), - 'list_projects': ('parent', 'page_token', 'page_size', 'show_deleted', ), - 'list_tag_bindings': ('parent', 'page_size', 'page_token', ), - 'list_tag_keys': ('parent', 'page_size', 'page_token', ), - 'list_tag_values': ('parent', 'page_size', 'page_token', ), - 'move_folder': ('name', 'destination_parent', ), - 'move_project': ('name', 'destination_parent', ), - 'search_folders': ('page_size', 'page_token', 'query', ), - 'search_organizations': ('page_size', 'page_token', 'query', ), - 'search_projects': ('query', 'page_token', 'page_size', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'undelete_folder': ('name', ), - 'undelete_project': ('name', ), - 'update_folder': ('folder', 'update_mask', ), - 'update_project': ('project', 'update_mask', ), - 'update_tag_key': ('tag_key', 'update_mask', 'validate_only', ), - 'update_tag_value': ('tag_value', 'update_mask', 'validate_only', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=resourcemanagerCallTransformer(), -): - """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 resourcemanager 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/v3/setup.py b/owl-bot-staging/v3/setup.py deleted file mode 100644 index 47ebfe5..0000000 --- a/owl-bot-staging/v3/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-resource-manager' - - -description = "Google Cloud Resource Manager API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/resourcemanager/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -url = "https://github.com/googleapis/python-resource-manager" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v3/testing/constraints-3.10.txt b/owl-bot-staging/v3/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v3/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/v3/testing/constraints-3.11.txt b/owl-bot-staging/v3/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v3/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/v3/testing/constraints-3.12.txt b/owl-bot-staging/v3/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v3/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/v3/testing/constraints-3.7.txt b/owl-bot-staging/v3/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf9..0000000 --- a/owl-bot-staging/v3/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v3/testing/constraints-3.8.txt b/owl-bot-staging/v3/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v3/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/v3/testing/constraints-3.9.txt b/owl-bot-staging/v3/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v3/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/v3/tests/__init__.py b/owl-bot-staging/v3/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v3/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v3/tests/unit/__init__.py b/owl-bot-staging/v3/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v3/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v3/tests/unit/gapic/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py deleted file mode 100644 index f4ce18c..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_folders.py +++ /dev/null @@ -1,6753 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.resourcemanager_v3.services.folders import FoldersAsyncClient -from google.cloud.resourcemanager_v3.services.folders import FoldersClient -from google.cloud.resourcemanager_v3.services.folders import pagers -from google.cloud.resourcemanager_v3.services.folders import transports -from google.cloud.resourcemanager_v3.types import folders -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 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert FoldersClient._get_default_mtls_endpoint(None) is None - assert FoldersClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FoldersClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FoldersClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FoldersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FoldersClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (FoldersClient, "grpc"), - (FoldersAsyncClient, "grpc_asyncio"), - (FoldersClient, "rest"), -]) -def test_folders_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FoldersGrpcTransport, "grpc"), - (transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.FoldersRestTransport, "rest"), -]) -def test_folders_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", [ - (FoldersClient, "grpc"), - (FoldersAsyncClient, "grpc_asyncio"), - (FoldersClient, "rest"), -]) -def test_folders_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -def test_folders_client_get_transport_class(): - transport = FoldersClient.get_transport_class() - available_transports = [ - transports.FoldersGrpcTransport, - transports.FoldersRestTransport, - ] - assert transport in available_transports - - transport = FoldersClient.get_transport_class("grpc") - assert transport == transports.FoldersGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FoldersClient, transports.FoldersGrpcTransport, "grpc"), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio"), - (FoldersClient, transports.FoldersRestTransport, "rest"), -]) -@mock.patch.object(FoldersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersClient)) -@mock.patch.object(FoldersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersAsyncClient)) -def test_folders_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(FoldersClient, '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(FoldersClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (FoldersClient, transports.FoldersGrpcTransport, "grpc", "true"), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FoldersClient, transports.FoldersGrpcTransport, "grpc", "false"), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (FoldersClient, transports.FoldersRestTransport, "rest", "true"), - (FoldersClient, transports.FoldersRestTransport, "rest", "false"), -]) -@mock.patch.object(FoldersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersClient)) -@mock.patch.object(FoldersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_folders_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - FoldersClient, FoldersAsyncClient -]) -@mock.patch.object(FoldersClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersClient)) -@mock.patch.object(FoldersAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FoldersAsyncClient)) -def test_folders_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FoldersClient, transports.FoldersGrpcTransport, "grpc"), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio"), - (FoldersClient, transports.FoldersRestTransport, "rest"), -]) -def test_folders_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (FoldersClient, transports.FoldersGrpcTransport, "grpc", grpc_helpers), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (FoldersClient, transports.FoldersRestTransport, "rest", None), -]) -def test_folders_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_folders_client_client_options_from_dict(): - with mock.patch('google.cloud.resourcemanager_v3.services.folders.transports.FoldersGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = FoldersClient( - 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", [ - (FoldersClient, transports.FoldersGrpcTransport, "grpc", grpc_helpers), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_folders_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=None, - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - folders.GetFolderRequest, - dict, -]) -def test_get_folder(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.Folder( - name='name_value', - parent='parent_value', - display_name='display_name_value', - state=folders.Folder.State.ACTIVE, - etag='etag_value', - ) - response = client.get_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.GetFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, folders.Folder) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.state == folders.Folder.State.ACTIVE - assert response.etag == 'etag_value' - - -def test_get_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_folder), - '__call__') as call: - client.get_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.GetFolderRequest() - -@pytest.mark.asyncio -async def test_get_folder_async(transport: str = 'grpc_asyncio', request_type=folders.GetFolderRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(folders.Folder( - name='name_value', - parent='parent_value', - display_name='display_name_value', - state=folders.Folder.State.ACTIVE, - etag='etag_value', - )) - response = await client.get_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.GetFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, folders.Folder) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.state == folders.Folder.State.ACTIVE - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_folder_async_from_dict(): - await test_get_folder_async(request_type=dict) - - -def test_get_folder_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.GetFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_folder), - '__call__') as call: - call.return_value = folders.Folder() - client.get_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_folder_field_headers_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.GetFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_folder), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.Folder()) - await client.get_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_folder_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.Folder() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_folder( - 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_folder_flattened_error(): - client = FoldersClient( - credentials=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_folder( - folders.GetFolderRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_folder_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.Folder() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.Folder()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_folder( - 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_folder_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_folder( - folders.GetFolderRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - folders.ListFoldersRequest, - dict, -]) -def test_list_folders(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.ListFoldersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_folders(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.ListFoldersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFoldersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_folders_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_folders), - '__call__') as call: - client.list_folders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.ListFoldersRequest() - -@pytest.mark.asyncio -async def test_list_folders_async(transport: str = 'grpc_asyncio', request_type=folders.ListFoldersRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(folders.ListFoldersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_folders(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.ListFoldersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFoldersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_folders_async_from_dict(): - await test_list_folders_async(request_type=dict) - - -def test_list_folders_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.ListFoldersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_folders( - 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_folders_flattened_error(): - client = FoldersClient( - credentials=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_folders( - folders.ListFoldersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_folders_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.ListFoldersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.ListFoldersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_folders( - 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_folders_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_folders( - folders.ListFoldersRequest(), - parent='parent_value', - ) - - -def test_list_folders_pager(transport_name: str = "grpc"): - client = FoldersClient( - 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_folders), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.ListFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_folders(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, folders.Folder) - for i in results) -def test_list_folders_pages(transport_name: str = "grpc"): - client = FoldersClient( - 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_folders), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.ListFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - pages = list(client.list_folders(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_folders_async_pager(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_folders), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.ListFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_folders(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, folders.Folder) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_folders_async_pages(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_folders), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.ListFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_folders(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - folders.SearchFoldersRequest, - dict, -]) -def test_search_folders(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.SearchFoldersResponse( - next_page_token='next_page_token_value', - ) - response = client.search_folders(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.SearchFoldersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchFoldersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_folders_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__') as call: - client.search_folders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.SearchFoldersRequest() - -@pytest.mark.asyncio -async def test_search_folders_async(transport: str = 'grpc_asyncio', request_type=folders.SearchFoldersRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(folders.SearchFoldersResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_folders(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.SearchFoldersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchFoldersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_folders_async_from_dict(): - await test_search_folders_async(request_type=dict) - - -def test_search_folders_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.SearchFoldersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_folders( - query='query_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - - -def test_search_folders_flattened_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_folders( - folders.SearchFoldersRequest(), - query='query_value', - ) - -@pytest.mark.asyncio -async def test_search_folders_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = folders.SearchFoldersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(folders.SearchFoldersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_folders( - query='query_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_folders_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.search_folders( - folders.SearchFoldersRequest(), - query='query_value', - ) - - -def test_search_folders_pager(transport_name: str = "grpc"): - client = FoldersClient( - 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.search_folders), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.SearchFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.search_folders(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, folders.Folder) - for i in results) -def test_search_folders_pages(transport_name: str = "grpc"): - client = FoldersClient( - 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.search_folders), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.SearchFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - pages = list(client.search_folders(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_search_folders_async_pager(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.SearchFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_folders(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, folders.Folder) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_folders_async_pages(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_folders), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.SearchFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_folders(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - folders.CreateFolderRequest, - dict, -]) -def test_create_folder(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.CreateFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_folder), - '__call__') as call: - client.create_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.CreateFolderRequest() - -@pytest.mark.asyncio -async def test_create_folder_async(transport: str = 'grpc_asyncio', request_type=folders.CreateFolderRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folder), - '__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_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.CreateFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_folder_async_from_dict(): - await test_create_folder_async(request_type=dict) - - -def test_create_folder_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_folder), - '__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_folder( - folder=folders.Folder(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].folder - mock_val = folders.Folder(name='name_value') - assert arg == mock_val - - -def test_create_folder_flattened_error(): - client = FoldersClient( - credentials=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_folder( - folders.CreateFolderRequest(), - folder=folders.Folder(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_folder_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_folder), - '__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_folder( - folder=folders.Folder(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].folder - mock_val = folders.Folder(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_folder_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_folder( - folders.CreateFolderRequest(), - folder=folders.Folder(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - folders.UpdateFolderRequest, - dict, -]) -def test_update_folder(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UpdateFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_folder), - '__call__') as call: - client.update_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UpdateFolderRequest() - -@pytest.mark.asyncio -async def test_update_folder_async(transport: str = 'grpc_asyncio', request_type=folders.UpdateFolderRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UpdateFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_folder_async_from_dict(): - await test_update_folder_async(request_type=dict) - - -def test_update_folder_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.UpdateFolderRequest() - - request.folder.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_folder), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'folder.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_folder_field_headers_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.UpdateFolderRequest() - - request.folder.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_folder), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'folder.name=name_value', - ) in kw['metadata'] - - -def test_update_folder_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_folder( - folder=folders.Folder(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].folder - mock_val = folders.Folder(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_folder_flattened_error(): - client = FoldersClient( - credentials=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_folder( - folders.UpdateFolderRequest(), - folder=folders.Folder(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_folder_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_folder( - folder=folders.Folder(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].folder - mock_val = folders.Folder(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_folder_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_folder( - folders.UpdateFolderRequest(), - folder=folders.Folder(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - folders.MoveFolderRequest, - dict, -]) -def test_move_folder(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.move_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.MoveFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_move_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__call__') as call: - client.move_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.MoveFolderRequest() - -@pytest.mark.asyncio -async def test_move_folder_async(transport: str = 'grpc_asyncio', request_type=folders.MoveFolderRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__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.move_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.MoveFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_move_folder_async_from_dict(): - await test_move_folder_async(request_type=dict) - - -def test_move_folder_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.MoveFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.move_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_move_folder_field_headers_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.MoveFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.move_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_move_folder_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__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.move_folder( - name='name_value', - destination_parent='destination_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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].destination_parent - mock_val = 'destination_parent_value' - assert arg == mock_val - - -def test_move_folder_flattened_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.move_folder( - folders.MoveFolderRequest(), - name='name_value', - destination_parent='destination_parent_value', - ) - -@pytest.mark.asyncio -async def test_move_folder_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_folder), - '__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.move_folder( - name='name_value', - destination_parent='destination_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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].destination_parent - mock_val = 'destination_parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_move_folder_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.move_folder( - folders.MoveFolderRequest(), - name='name_value', - destination_parent='destination_parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - folders.DeleteFolderRequest, - dict, -]) -def test_delete_folder(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.DeleteFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - client.delete_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.DeleteFolderRequest() - -@pytest.mark.asyncio -async def test_delete_folder_async(transport: str = 'grpc_asyncio', request_type=folders.DeleteFolderRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.DeleteFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_folder_async_from_dict(): - await test_delete_folder_async(request_type=dict) - - -def test_delete_folder_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.DeleteFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_folder_field_headers_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.DeleteFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_folder_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_folder( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_folder_flattened_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_folder( - folders.DeleteFolderRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_folder_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_folder( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_folder_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_folder( - folders.DeleteFolderRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - folders.UndeleteFolderRequest, - dict, -]) -def test_undelete_folder(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undelete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UndeleteFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undelete_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__call__') as call: - client.undelete_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UndeleteFolderRequest() - -@pytest.mark.asyncio -async def test_undelete_folder_async(transport: str = 'grpc_asyncio', request_type=folders.UndeleteFolderRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__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.undelete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UndeleteFolderRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undelete_folder_async_from_dict(): - await test_undelete_folder_async(request_type=dict) - - -def test_undelete_folder_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.UndeleteFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undelete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_undelete_folder_field_headers_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = folders.UndeleteFolderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undelete_folder(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_undelete_folder_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__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.undelete_folder( - 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_undelete_folder_flattened_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undelete_folder( - folders.UndeleteFolderRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_undelete_folder_flattened_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_folder), - '__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.undelete_folder( - 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_undelete_folder_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.undelete_folder( - folders.UndeleteFolderRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = FoldersClient( - 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() - - -def test_get_iam_policy_flattened(): - client = FoldersClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = FoldersClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = FoldersAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = FoldersClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = FoldersClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = FoldersAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = FoldersClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = FoldersClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = FoldersAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - folders.GetFolderRequest, - dict, -]) -def test_get_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = folders.Folder( - name='name_value', - parent='parent_value', - display_name='display_name_value', - state=folders.Folder.State.ACTIVE, - etag='etag_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = folders.Folder.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_folder(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, folders.Folder) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.display_name == 'display_name_value' - assert response.state == folders.Folder.State.ACTIVE - assert response.etag == 'etag_value' - - -def test_get_folder_rest_required_fields(request_type=folders.GetFolderRequest): - transport_class = transports.FoldersRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_folder._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_folder._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 = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = folders.Folder() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = folders.Folder.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_folder(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_folder_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_folder._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FoldersRestInterceptor, "post_get_folder") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_get_folder") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.GetFolderRequest.pb(folders.GetFolderRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = folders.Folder.to_json(folders.Folder()) - - request = folders.GetFolderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = folders.Folder() - - client.get_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_folder_rest_bad_request(transport: str = 'rest', request_type=folders.GetFolderRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_folder(request) - - -def test_get_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = folders.Folder() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = folders.Folder.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_folder(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=folders/*}" % client.transport._host, args[1]) - - -def test_get_folder_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.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_folder( - folders.GetFolderRequest(), - name='name_value', - ) - - -def test_get_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - folders.ListFoldersRequest, - dict, -]) -def test_list_folders_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = folders.ListFoldersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = folders.ListFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_folders(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFoldersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_folders_rest_required_fields(request_type=folders.ListFoldersRequest): - transport_class = transports.FoldersRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "parent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_folders._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "parent" in jsonified_request - assert jsonified_request["parent"] == request_init["parent"] - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_folders._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "parent", "show_deleted", )) - 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 = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = folders.ListFoldersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = folders.ListFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_folders(request) - - expected_params = [ - ( - "parent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_folders_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_folders._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", "showDeleted", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_folders_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FoldersRestInterceptor, "post_list_folders") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_list_folders") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.ListFoldersRequest.pb(folders.ListFoldersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = folders.ListFoldersResponse.to_json(folders.ListFoldersResponse()) - - request = folders.ListFoldersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = folders.ListFoldersResponse() - - client.list_folders(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_folders_rest_bad_request(transport: str = 'rest', request_type=folders.ListFoldersRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_folders(request) - - -def test_list_folders_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = folders.ListFoldersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = folders.ListFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_folders(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/folders" % client.transport._host, args[1]) - - -def test_list_folders_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.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_folders( - folders.ListFoldersRequest(), - parent='parent_value', - ) - - -def test_list_folders_rest_pager(transport: str = 'rest'): - client = FoldersClient( - 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 = ( - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.ListFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.ListFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(folders.ListFoldersResponse.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 = {} - - pager = client.list_folders(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, folders.Folder) - for i in results) - - pages = list(client.list_folders(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - folders.SearchFoldersRequest, - dict, -]) -def test_search_folders_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = folders.SearchFoldersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = folders.SearchFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_folders(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchFoldersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_folders_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FoldersRestInterceptor, "post_search_folders") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_search_folders") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.SearchFoldersRequest.pb(folders.SearchFoldersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = folders.SearchFoldersResponse.to_json(folders.SearchFoldersResponse()) - - request = folders.SearchFoldersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = folders.SearchFoldersResponse() - - client.search_folders(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_folders_rest_bad_request(transport: str = 'rest', request_type=folders.SearchFoldersRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search_folders(request) - - -def test_search_folders_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = folders.SearchFoldersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - query='query_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = folders.SearchFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_folders(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/folders:search" % client.transport._host, args[1]) - - -def test_search_folders_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_folders( - folders.SearchFoldersRequest(), - query='query_value', - ) - - -def test_search_folders_rest_pager(transport: str = 'rest'): - client = FoldersClient( - 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 = ( - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - folders.Folder(), - ], - next_page_token='abc', - ), - folders.SearchFoldersResponse( - folders=[], - next_page_token='def', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - ], - next_page_token='ghi', - ), - folders.SearchFoldersResponse( - folders=[ - folders.Folder(), - folders.Folder(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(folders.SearchFoldersResponse.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 = {} - - pager = client.search_folders(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, folders.Folder) - for i in results) - - pages = list(client.search_folders(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - folders.CreateFolderRequest, - dict, -]) -def test_create_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["folder"] = {'name': 'name_value', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_folder_rest_required_fields(request_type=folders.CreateFolderRequest): - transport_class = transports.FoldersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_folder._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()).create_folder._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = FoldersClient( - 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_folder(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_folder_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_folder._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("folder", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_create_folder") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_create_folder") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.CreateFolderRequest.pb(folders.CreateFolderRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = folders.CreateFolderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_folder_rest_bad_request(transport: str = 'rest', request_type=folders.CreateFolderRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["folder"] = {'name': 'name_value', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_folder(request) - - -def test_create_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {} - - # get truthy value for each flattened field - mock_args = dict( - folder=folders.Folder(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_folder(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/folders" % client.transport._host, args[1]) - - -def test_create_folder_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.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_folder( - folders.CreateFolderRequest(), - folder=folders.Folder(name='name_value'), - ) - - -def test_create_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - folders.UpdateFolderRequest, - dict, -]) -def test_update_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'folder': {'name': 'folders/sample1'}} - request_init["folder"] = {'name': 'folders/sample1', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_folder_rest_required_fields(request_type=folders.UpdateFolderRequest): - transport_class = transports.FoldersRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_folder._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_folder._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 = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_folder(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_folder_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_folder._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("folder", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_update_folder") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_update_folder") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.UpdateFolderRequest.pb(folders.UpdateFolderRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = folders.UpdateFolderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_folder_rest_bad_request(transport: str = 'rest', request_type=folders.UpdateFolderRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'folder': {'name': 'folders/sample1'}} - request_init["folder"] = {'name': 'folders/sample1', 'parent': 'parent_value', 'display_name': 'display_name_value', 'state': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_folder(request) - - -def test_update_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {'folder': {'name': 'folders/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - folder=folders.Folder(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_folder(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{folder.name=folders/*}" % client.transport._host, args[1]) - - -def test_update_folder_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.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_folder( - folders.UpdateFolderRequest(), - folder=folders.Folder(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - folders.MoveFolderRequest, - dict, -]) -def test_move_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.move_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_move_folder_rest_required_fields(request_type=folders.MoveFolderRequest): - transport_class = transports.FoldersRestTransport - - request_init = {} - request_init["name"] = "" - request_init["destination_parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_folder._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["destinationParent"] = 'destination_parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_folder._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 "destinationParent" in jsonified_request - assert jsonified_request["destinationParent"] == 'destination_parent_value' - - client = FoldersClient( - 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.move_folder(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_move_folder_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.move_folder._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "destinationParent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_move_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_move_folder") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_move_folder") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.MoveFolderRequest.pb(folders.MoveFolderRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = folders.MoveFolderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.move_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_move_folder_rest_bad_request(transport: str = 'rest', request_type=folders.MoveFolderRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.move_folder(request) - - -def test_move_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - destination_parent='destination_parent_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.move_folder(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=folders/*}:move" % client.transport._host, args[1]) - - -def test_move_folder_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.move_folder( - folders.MoveFolderRequest(), - name='name_value', - destination_parent='destination_parent_value', - ) - - -def test_move_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - folders.DeleteFolderRequest, - dict, -]) -def test_delete_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_folder_rest_required_fields(request_type=folders.DeleteFolderRequest): - transport_class = transports.FoldersRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_folder._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_folder._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 = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_folder(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_folder_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_folder._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_delete_folder") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_delete_folder") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.DeleteFolderRequest.pb(folders.DeleteFolderRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = folders.DeleteFolderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_folder_rest_bad_request(transport: str = 'rest', request_type=folders.DeleteFolderRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_folder(request) - - -def test_delete_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_folder(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=folders/*}" % client.transport._host, args[1]) - - -def test_delete_folder_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_folder( - folders.DeleteFolderRequest(), - name='name_value', - ) - - -def test_delete_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - folders.UndeleteFolderRequest, - dict, -]) -def test_undelete_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undelete_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undelete_folder_rest_required_fields(request_type=folders.UndeleteFolderRequest): - transport_class = transports.FoldersRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undelete_folder._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()).undelete_folder._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 = FoldersClient( - 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.undelete_folder(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undelete_folder_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undelete_folder._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_undelete_folder") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_undelete_folder") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.UndeleteFolderRequest.pb(folders.UndeleteFolderRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = folders.UndeleteFolderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undelete_folder(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undelete_folder_rest_bad_request(transport: str = 'rest', request_type=folders.UndeleteFolderRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undelete_folder(request) - - -def test_undelete_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.undelete_folder(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=folders/*}:undelete" % client.transport._host, args[1]) - - -def test_undelete_folder_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undelete_folder( - folders.UndeleteFolderRequest(), - name='name_value', - ) - - -def test_undelete_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'folders/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.FoldersRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FoldersRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=folders/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'folders/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.FoldersRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FoldersRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=folders/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'folders/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.FoldersRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.FoldersRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.FoldersRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.FoldersRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'folders/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'folders/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=folders/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FoldersClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FoldersClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FoldersClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FoldersClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FoldersClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.FoldersGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.FoldersGrpcTransport, - transports.FoldersGrpcAsyncIOTransport, - transports.FoldersRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = FoldersClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FoldersGrpcTransport, - ) - -def test_folders_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.FoldersTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_folders_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.resourcemanager_v3.services.folders.transports.FoldersTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.FoldersTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_folder', - 'list_folders', - 'search_folders', - 'create_folder', - 'update_folder', - 'move_folder', - 'delete_folder', - 'undelete_folder', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - 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_folders_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.resourcemanager_v3.services.folders.transports.FoldersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FoldersTransport( - 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/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -def test_folders_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.resourcemanager_v3.services.folders.transports.FoldersTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FoldersTransport() - adc.assert_called_once() - - -def test_folders_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) - FoldersClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FoldersGrpcTransport, - transports.FoldersGrpcAsyncIOTransport, - ], -) -def test_folders_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/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FoldersGrpcTransport, - transports.FoldersGrpcAsyncIOTransport, - transports.FoldersRestTransport, - ], -) -def test_folders_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.FoldersGrpcTransport, grpc_helpers), - (transports.FoldersGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_folders_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( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.FoldersGrpcTransport, transports.FoldersGrpcAsyncIOTransport]) -def test_folders_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_folders_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.FoldersRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_folders_rest_lro_client(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_folders_host_no_port(transport_name): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_folders_host_with_port(transport_name): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_folders_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = FoldersClient( - credentials=creds1, - transport=transport_name, - ) - client2 = FoldersClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_folder._session - session2 = client2.transport.get_folder._session - assert session1 != session2 - session1 = client1.transport.list_folders._session - session2 = client2.transport.list_folders._session - assert session1 != session2 - session1 = client1.transport.search_folders._session - session2 = client2.transport.search_folders._session - assert session1 != session2 - session1 = client1.transport.create_folder._session - session2 = client2.transport.create_folder._session - assert session1 != session2 - session1 = client1.transport.update_folder._session - session2 = client2.transport.update_folder._session - assert session1 != session2 - session1 = client1.transport.move_folder._session - session2 = client2.transport.move_folder._session - assert session1 != session2 - session1 = client1.transport.delete_folder._session - session2 = client2.transport.delete_folder._session - assert session1 != session2 - session1 = client1.transport.undelete_folder._session - session2 = client2.transport.undelete_folder._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 -def test_folders_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FoldersGrpcTransport( - 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_folders_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FoldersGrpcAsyncIOTransport( - 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.FoldersGrpcTransport, transports.FoldersGrpcAsyncIOTransport]) -def test_folders_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.FoldersGrpcTransport, transports.FoldersGrpcAsyncIOTransport]) -def test_folders_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_folders_grpc_lro_client(): - client = FoldersClient( - 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_folders_grpc_lro_async_client(): - client = FoldersAsyncClient( - 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_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = FoldersClient.folder_path(folder) - assert expected == actual - - -def test_parse_folder_path(): - expected = { - "folder": "clam", - } - path = FoldersClient.folder_path(**expected) - - # Check that the path construction is reversible. - actual = FoldersClient.parse_folder_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = FoldersClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = FoldersClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = FoldersClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = FoldersClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = FoldersClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = FoldersClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FoldersClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = FoldersClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = FoldersClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = FoldersClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = FoldersClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = FoldersClient.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 = FoldersClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = FoldersClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = FoldersClient.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.FoldersTransport, '_prep_wrapped_messages') as prep: - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.FoldersTransport, '_prep_wrapped_messages') as prep: - transport_class = FoldersClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = FoldersClient( - 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", [ - (FoldersClient, transports.FoldersGrpcTransport), - (FoldersAsyncClient, transports.FoldersGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py deleted file mode 100644 index 5c90e69..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_organizations.py +++ /dev/null @@ -1,3765 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.resourcemanager_v3.services.organizations import OrganizationsAsyncClient -from google.cloud.resourcemanager_v3.services.organizations import OrganizationsClient -from google.cloud.resourcemanager_v3.services.organizations import pagers -from google.cloud.resourcemanager_v3.services.organizations import transports -from google.cloud.resourcemanager_v3.types import organizations -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.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert OrganizationsClient._get_default_mtls_endpoint(None) is None - assert OrganizationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OrganizationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OrganizationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OrganizationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OrganizationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (OrganizationsClient, "grpc"), - (OrganizationsAsyncClient, "grpc_asyncio"), - (OrganizationsClient, "rest"), -]) -def test_organizations_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.OrganizationsGrpcTransport, "grpc"), - (transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.OrganizationsRestTransport, "rest"), -]) -def test_organizations_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", [ - (OrganizationsClient, "grpc"), - (OrganizationsAsyncClient, "grpc_asyncio"), - (OrganizationsClient, "rest"), -]) -def test_organizations_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -def test_organizations_client_get_transport_class(): - transport = OrganizationsClient.get_transport_class() - available_transports = [ - transports.OrganizationsGrpcTransport, - transports.OrganizationsRestTransport, - ] - assert transport in available_transports - - transport = OrganizationsClient.get_transport_class("grpc") - assert transport == transports.OrganizationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc"), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio"), - (OrganizationsClient, transports.OrganizationsRestTransport, "rest"), -]) -@mock.patch.object(OrganizationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsClient)) -@mock.patch.object(OrganizationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsAsyncClient)) -def test_organizations_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(OrganizationsClient, '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(OrganizationsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", "true"), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", "false"), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (OrganizationsClient, transports.OrganizationsRestTransport, "rest", "true"), - (OrganizationsClient, transports.OrganizationsRestTransport, "rest", "false"), -]) -@mock.patch.object(OrganizationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsClient)) -@mock.patch.object(OrganizationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_organizations_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - OrganizationsClient, OrganizationsAsyncClient -]) -@mock.patch.object(OrganizationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsClient)) -@mock.patch.object(OrganizationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationsAsyncClient)) -def test_organizations_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc"), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio"), - (OrganizationsClient, transports.OrganizationsRestTransport, "rest"), -]) -def test_organizations_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", grpc_helpers), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (OrganizationsClient, transports.OrganizationsRestTransport, "rest", None), -]) -def test_organizations_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_organizations_client_client_options_from_dict(): - with mock.patch('google.cloud.resourcemanager_v3.services.organizations.transports.OrganizationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = OrganizationsClient( - 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", [ - (OrganizationsClient, transports.OrganizationsGrpcTransport, "grpc", grpc_helpers), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_organizations_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=None, - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - organizations.GetOrganizationRequest, - dict, -]) -def test_get_organization(request_type, transport: str = 'grpc'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organizations.Organization( - name='name_value', - display_name='display_name_value', - state=organizations.Organization.State.ACTIVE, - etag='etag_value', - directory_customer_id='directory_customer_id_value', - ) - response = client.get_organization(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.GetOrganizationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organizations.Organization) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == organizations.Organization.State.ACTIVE - assert response.etag == 'etag_value' - - -def test_get_organization_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization), - '__call__') as call: - client.get_organization() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.GetOrganizationRequest() - -@pytest.mark.asyncio -async def test_get_organization_async(transport: str = 'grpc_asyncio', request_type=organizations.GetOrganizationRequest): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_organization), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organizations.Organization( - name='name_value', - display_name='display_name_value', - state=organizations.Organization.State.ACTIVE, - etag='etag_value', - )) - response = await client.get_organization(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.GetOrganizationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organizations.Organization) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == organizations.Organization.State.ACTIVE - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_organization_async_from_dict(): - await test_get_organization_async(request_type=dict) - - -def test_get_organization_field_headers(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = organizations.GetOrganizationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization), - '__call__') as call: - call.return_value = organizations.Organization() - client.get_organization(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_organization_field_headers_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = organizations.GetOrganizationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organizations.Organization()) - await client.get_organization(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_organization_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organizations.Organization() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization( - 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_organization_flattened_error(): - client = OrganizationsClient( - credentials=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_organization( - organizations.GetOrganizationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_organization_flattened_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organizations.Organization() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organizations.Organization()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization( - 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_organization_flattened_error_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_organization( - organizations.GetOrganizationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - organizations.SearchOrganizationsRequest, - dict, -]) -def test_search_organizations(request_type, transport: str = 'grpc'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organizations.SearchOrganizationsResponse( - next_page_token='next_page_token_value', - ) - response = client.search_organizations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.SearchOrganizationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchOrganizationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_organizations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__') as call: - client.search_organizations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.SearchOrganizationsRequest() - -@pytest.mark.asyncio -async def test_search_organizations_async(transport: str = 'grpc_asyncio', request_type=organizations.SearchOrganizationsRequest): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organizations.SearchOrganizationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_organizations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.SearchOrganizationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchOrganizationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_organizations_async_from_dict(): - await test_search_organizations_async(request_type=dict) - - -def test_search_organizations_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organizations.SearchOrganizationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_organizations( - query='query_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - - -def test_search_organizations_flattened_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_organizations( - organizations.SearchOrganizationsRequest(), - query='query_value', - ) - -@pytest.mark.asyncio -async def test_search_organizations_flattened_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organizations.SearchOrganizationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organizations.SearchOrganizationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_organizations( - query='query_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_organizations_flattened_error_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.search_organizations( - organizations.SearchOrganizationsRequest(), - query='query_value', - ) - - -def test_search_organizations_pager(transport_name: str = "grpc"): - client = OrganizationsClient( - 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.search_organizations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - organizations.Organization(), - ], - next_page_token='abc', - ), - organizations.SearchOrganizationsResponse( - organizations=[], - next_page_token='def', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - ], - next_page_token='ghi', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.search_organizations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, organizations.Organization) - for i in results) -def test_search_organizations_pages(transport_name: str = "grpc"): - client = OrganizationsClient( - 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.search_organizations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - organizations.Organization(), - ], - next_page_token='abc', - ), - organizations.SearchOrganizationsResponse( - organizations=[], - next_page_token='def', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - ], - next_page_token='ghi', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - ], - ), - RuntimeError, - ) - pages = list(client.search_organizations(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_search_organizations_async_pager(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - organizations.Organization(), - ], - next_page_token='abc', - ), - organizations.SearchOrganizationsResponse( - organizations=[], - next_page_token='def', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - ], - next_page_token='ghi', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_organizations(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, organizations.Organization) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_organizations_async_pages(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - organizations.Organization(), - ], - next_page_token='abc', - ), - organizations.SearchOrganizationsResponse( - organizations=[], - next_page_token='def', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - ], - next_page_token='ghi', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_organizations(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = OrganizationsClient( - 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() - - -def test_get_iam_policy_flattened(): - client = OrganizationsClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = OrganizationsClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = OrganizationsAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = OrganizationsClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = OrganizationsClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = OrganizationsAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = OrganizationsClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = OrganizationsClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = OrganizationsAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - organizations.GetOrganizationRequest, - dict, -]) -def test_get_organization_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/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 = organizations.Organization( - name='name_value', - display_name='display_name_value', - state=organizations.Organization.State.ACTIVE, - etag='etag_value', - directory_customer_id='directory_customer_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = organizations.Organization.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_organization(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organizations.Organization) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.state == organizations.Organization.State.ACTIVE - assert response.etag == 'etag_value' - - -def test_get_organization_rest_required_fields(request_type=organizations.GetOrganizationRequest): - transport_class = transports.OrganizationsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_organization._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_organization._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 = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = organizations.Organization() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = organizations.Organization.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_organization(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_organization_rest_unset_required_fields(): - transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_organization._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "post_get_organization") as post, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "pre_get_organization") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = organizations.GetOrganizationRequest.pb(organizations.GetOrganizationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organizations.Organization.to_json(organizations.Organization()) - - request = organizations.GetOrganizationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organizations.Organization() - - client.get_organization(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_rest_bad_request(transport: str = 'rest', request_type=organizations.GetOrganizationRequest): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_organization(request) - - -def test_get_organization_rest_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organizations.Organization() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = organizations.Organization.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_organization(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=organizations/*}" % client.transport._host, args[1]) - - -def test_get_organization_rest_flattened_error(transport: str = 'rest'): - client = OrganizationsClient( - credentials=ga_credentials.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_organization( - organizations.GetOrganizationRequest(), - name='name_value', - ) - - -def test_get_organization_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - organizations.SearchOrganizationsRequest, - dict, -]) -def test_search_organizations_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organizations.SearchOrganizationsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = organizations.SearchOrganizationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_organizations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchOrganizationsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_organizations_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "post_search_organizations") as post, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "pre_search_organizations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = organizations.SearchOrganizationsRequest.pb(organizations.SearchOrganizationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = organizations.SearchOrganizationsResponse.to_json(organizations.SearchOrganizationsResponse()) - - request = organizations.SearchOrganizationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organizations.SearchOrganizationsResponse() - - client.search_organizations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_organizations_rest_bad_request(transport: str = 'rest', request_type=organizations.SearchOrganizationsRequest): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search_organizations(request) - - -def test_search_organizations_rest_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = organizations.SearchOrganizationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - query='query_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = organizations.SearchOrganizationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_organizations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/organizations:search" % client.transport._host, args[1]) - - -def test_search_organizations_rest_flattened_error(transport: str = 'rest'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_organizations( - organizations.SearchOrganizationsRequest(), - query='query_value', - ) - - -def test_search_organizations_rest_pager(transport: str = 'rest'): - client = OrganizationsClient( - 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 = ( - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - organizations.Organization(), - ], - next_page_token='abc', - ), - organizations.SearchOrganizationsResponse( - organizations=[], - next_page_token='def', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - ], - next_page_token='ghi', - ), - organizations.SearchOrganizationsResponse( - organizations=[ - organizations.Organization(), - organizations.Organization(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(organizations.SearchOrganizationsResponse.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 = {} - - pager = client.search_organizations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, organizations.Organization) - for i in results) - - pages = list(client.search_organizations(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.OrganizationsRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=organizations/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = OrganizationsClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.OrganizationsRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=organizations/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.OrganizationsRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.OrganizationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.OrganizationsRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'organizations/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'organizations/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=organizations/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = OrganizationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.OrganizationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.OrganizationsGrpcTransport, - transports.OrganizationsGrpcAsyncIOTransport, - transports.OrganizationsRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = OrganizationsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.OrganizationsGrpcTransport, - ) - -def test_organizations_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.OrganizationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_organizations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.resourcemanager_v3.services.organizations.transports.OrganizationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.OrganizationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_organization', - 'search_organizations', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - 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_organizations_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.resourcemanager_v3.services.organizations.transports.OrganizationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OrganizationsTransport( - 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/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -def test_organizations_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.resourcemanager_v3.services.organizations.transports.OrganizationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OrganizationsTransport() - adc.assert_called_once() - - -def test_organizations_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) - OrganizationsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.OrganizationsGrpcTransport, - transports.OrganizationsGrpcAsyncIOTransport, - ], -) -def test_organizations_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/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.OrganizationsGrpcTransport, - transports.OrganizationsGrpcAsyncIOTransport, - transports.OrganizationsRestTransport, - ], -) -def test_organizations_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.OrganizationsGrpcTransport, grpc_helpers), - (transports.OrganizationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_organizations_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( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.OrganizationsGrpcTransport, transports.OrganizationsGrpcAsyncIOTransport]) -def test_organizations_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_organizations_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.OrganizationsRestTransport ( - 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_organizations_host_no_port(transport_name): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_organizations_host_with_port(transport_name): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_organizations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = OrganizationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = OrganizationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_organization._session - session2 = client2.transport.get_organization._session - assert session1 != session2 - session1 = client1.transport.search_organizations._session - session2 = client2.transport.search_organizations._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 -def test_organizations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OrganizationsGrpcTransport( - 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_organizations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OrganizationsGrpcAsyncIOTransport( - 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.OrganizationsGrpcTransport, transports.OrganizationsGrpcAsyncIOTransport]) -def test_organizations_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.OrganizationsGrpcTransport, transports.OrganizationsGrpcAsyncIOTransport]) -def test_organizations_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_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OrganizationsClient.organization_path(organization) - assert expected == actual - - -def test_parse_organization_path(): - expected = { - "organization": "clam", - } - path = OrganizationsClient.organization_path(**expected) - - # Check that the path construction is reversible. - actual = OrganizationsClient.parse_organization_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OrganizationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = OrganizationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = OrganizationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = OrganizationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = OrganizationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = OrganizationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OrganizationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = OrganizationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = OrganizationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = OrganizationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = OrganizationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = OrganizationsClient.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 = OrganizationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = OrganizationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = OrganizationsClient.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.OrganizationsTransport, '_prep_wrapped_messages') as prep: - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.OrganizationsTransport, '_prep_wrapped_messages') as prep: - transport_class = OrganizationsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = OrganizationsClient( - 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", [ - (OrganizationsClient, transports.OrganizationsGrpcTransport), - (OrganizationsAsyncClient, transports.OrganizationsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py deleted file mode 100644 index a1e8b03..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_projects.py +++ /dev/null @@ -1,6759 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.resourcemanager_v3.services.projects import ProjectsAsyncClient -from google.cloud.resourcemanager_v3.services.projects import ProjectsClient -from google.cloud.resourcemanager_v3.services.projects import pagers -from google.cloud.resourcemanager_v3.services.projects import transports -from google.cloud.resourcemanager_v3.types import projects -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 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProjectsClient._get_default_mtls_endpoint(None) is None - assert ProjectsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProjectsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProjectsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProjectsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProjectsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProjectsClient, "grpc"), - (ProjectsAsyncClient, "grpc_asyncio"), - (ProjectsClient, "rest"), -]) -def test_projects_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProjectsGrpcTransport, "grpc"), - (transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProjectsRestTransport, "rest"), -]) -def test_projects_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", [ - (ProjectsClient, "grpc"), - (ProjectsAsyncClient, "grpc_asyncio"), - (ProjectsClient, "rest"), -]) -def test_projects_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -def test_projects_client_get_transport_class(): - transport = ProjectsClient.get_transport_class() - available_transports = [ - transports.ProjectsGrpcTransport, - transports.ProjectsRestTransport, - ] - assert transport in available_transports - - transport = ProjectsClient.get_transport_class("grpc") - assert transport == transports.ProjectsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProjectsClient, transports.ProjectsGrpcTransport, "grpc"), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio"), - (ProjectsClient, transports.ProjectsRestTransport, "rest"), -]) -@mock.patch.object(ProjectsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsClient)) -@mock.patch.object(ProjectsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsAsyncClient)) -def test_projects_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(ProjectsClient, '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(ProjectsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", "true"), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", "false"), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ProjectsClient, transports.ProjectsRestTransport, "rest", "true"), - (ProjectsClient, transports.ProjectsRestTransport, "rest", "false"), -]) -@mock.patch.object(ProjectsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsClient)) -@mock.patch.object(ProjectsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_projects_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProjectsClient, ProjectsAsyncClient -]) -@mock.patch.object(ProjectsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsClient)) -@mock.patch.object(ProjectsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectsAsyncClient)) -def test_projects_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProjectsClient, transports.ProjectsGrpcTransport, "grpc"), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio"), - (ProjectsClient, transports.ProjectsRestTransport, "rest"), -]) -def test_projects_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", grpc_helpers), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ProjectsClient, transports.ProjectsRestTransport, "rest", None), -]) -def test_projects_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_projects_client_client_options_from_dict(): - with mock.patch('google.cloud.resourcemanager_v3.services.projects.transports.ProjectsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProjectsClient( - 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", [ - (ProjectsClient, transports.ProjectsGrpcTransport, "grpc", grpc_helpers), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_projects_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=None, - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - projects.GetProjectRequest, - dict, -]) -def test_get_project(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.Project( - name='name_value', - parent='parent_value', - project_id='project_id_value', - state=projects.Project.State.ACTIVE, - display_name='display_name_value', - etag='etag_value', - ) - response = client.get_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.GetProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, projects.Project) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.project_id == 'project_id_value' - assert response.state == projects.Project.State.ACTIVE - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -def test_get_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_project), - '__call__') as call: - client.get_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.GetProjectRequest() - -@pytest.mark.asyncio -async def test_get_project_async(transport: str = 'grpc_asyncio', request_type=projects.GetProjectRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(projects.Project( - name='name_value', - parent='parent_value', - project_id='project_id_value', - state=projects.Project.State.ACTIVE, - display_name='display_name_value', - etag='etag_value', - )) - response = await client.get_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.GetProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, projects.Project) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.project_id == 'project_id_value' - assert response.state == projects.Project.State.ACTIVE - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_project_async_from_dict(): - await test_get_project_async(request_type=dict) - - -def test_get_project_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.GetProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_project), - '__call__') as call: - call.return_value = projects.Project() - client.get_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_project_field_headers_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.GetProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_project), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.Project()) - await client.get_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_project_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.Project() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_project( - 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_project_flattened_error(): - client = ProjectsClient( - credentials=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_project( - projects.GetProjectRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_project_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.Project() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.Project()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_project( - 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_project_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_project( - projects.GetProjectRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - projects.ListProjectsRequest, - dict, -]) -def test_list_projects(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.ListProjectsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_projects(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.ListProjectsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProjectsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_projects_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_projects), - '__call__') as call: - client.list_projects() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.ListProjectsRequest() - -@pytest.mark.asyncio -async def test_list_projects_async(transport: str = 'grpc_asyncio', request_type=projects.ListProjectsRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(projects.ListProjectsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_projects(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.ListProjectsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProjectsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_projects_async_from_dict(): - await test_list_projects_async(request_type=dict) - - -def test_list_projects_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.ListProjectsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_projects( - 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_projects_flattened_error(): - client = ProjectsClient( - credentials=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_projects( - projects.ListProjectsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_projects_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.ListProjectsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.ListProjectsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_projects( - 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_projects_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_projects( - projects.ListProjectsRequest(), - parent='parent_value', - ) - - -def test_list_projects_pager(transport_name: str = "grpc"): - client = ProjectsClient( - 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_projects), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.ListProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_projects(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, projects.Project) - for i in results) -def test_list_projects_pages(transport_name: str = "grpc"): - client = ProjectsClient( - 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_projects), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.ListProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - pages = list(client.list_projects(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_projects_async_pager(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_projects), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.ListProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_projects(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, projects.Project) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_projects_async_pages(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_projects), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.ListProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_projects(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - projects.SearchProjectsRequest, - dict, -]) -def test_search_projects(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.SearchProjectsResponse( - next_page_token='next_page_token_value', - ) - response = client.search_projects(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.SearchProjectsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchProjectsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_projects_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__') as call: - client.search_projects() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.SearchProjectsRequest() - -@pytest.mark.asyncio -async def test_search_projects_async(transport: str = 'grpc_asyncio', request_type=projects.SearchProjectsRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(projects.SearchProjectsResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_projects(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.SearchProjectsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchProjectsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_projects_async_from_dict(): - await test_search_projects_async(request_type=dict) - - -def test_search_projects_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.SearchProjectsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_projects( - query='query_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - - -def test_search_projects_flattened_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_projects( - projects.SearchProjectsRequest(), - query='query_value', - ) - -@pytest.mark.asyncio -async def test_search_projects_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = projects.SearchProjectsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(projects.SearchProjectsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_projects( - query='query_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_projects_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.search_projects( - projects.SearchProjectsRequest(), - query='query_value', - ) - - -def test_search_projects_pager(transport_name: str = "grpc"): - client = ProjectsClient( - 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.search_projects), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.SearchProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.search_projects(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, projects.Project) - for i in results) -def test_search_projects_pages(transport_name: str = "grpc"): - client = ProjectsClient( - 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.search_projects), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.SearchProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - pages = list(client.search_projects(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_search_projects_async_pager(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.SearchProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_projects(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, projects.Project) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_projects_async_pages(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_projects), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.SearchProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.search_projects(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - projects.CreateProjectRequest, - dict, -]) -def test_create_project(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.CreateProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_project), - '__call__') as call: - client.create_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.CreateProjectRequest() - -@pytest.mark.asyncio -async def test_create_project_async(transport: str = 'grpc_asyncio', request_type=projects.CreateProjectRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_project), - '__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_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.CreateProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_project_async_from_dict(): - await test_create_project_async(request_type=dict) - - -def test_create_project_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_project), - '__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_project( - project=projects.Project(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].project - mock_val = projects.Project(name='name_value') - assert arg == mock_val - - -def test_create_project_flattened_error(): - client = ProjectsClient( - credentials=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_project( - projects.CreateProjectRequest(), - project=projects.Project(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_project_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_project), - '__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_project( - project=projects.Project(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].project - mock_val = projects.Project(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_project_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_project( - projects.CreateProjectRequest(), - project=projects.Project(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - projects.UpdateProjectRequest, - dict, -]) -def test_update_project(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UpdateProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_project), - '__call__') as call: - client.update_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UpdateProjectRequest() - -@pytest.mark.asyncio -async def test_update_project_async(transport: str = 'grpc_asyncio', request_type=projects.UpdateProjectRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UpdateProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_project_async_from_dict(): - await test_update_project_async(request_type=dict) - - -def test_update_project_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.UpdateProjectRequest() - - request.project.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_project), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_project_field_headers_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.UpdateProjectRequest() - - request.project.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_project), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'project.name=name_value', - ) in kw['metadata'] - - -def test_update_project_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_project( - project=projects.Project(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].project - mock_val = projects.Project(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_project_flattened_error(): - client = ProjectsClient( - credentials=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_project( - projects.UpdateProjectRequest(), - project=projects.Project(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_project_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_project( - project=projects.Project(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].project - mock_val = projects.Project(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_project_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_project( - projects.UpdateProjectRequest(), - project=projects.Project(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - projects.MoveProjectRequest, - dict, -]) -def test_move_project(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.move_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.MoveProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_move_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__call__') as call: - client.move_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.MoveProjectRequest() - -@pytest.mark.asyncio -async def test_move_project_async(transport: str = 'grpc_asyncio', request_type=projects.MoveProjectRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__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.move_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.MoveProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_move_project_async_from_dict(): - await test_move_project_async(request_type=dict) - - -def test_move_project_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.MoveProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.move_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_move_project_field_headers_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.MoveProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.move_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_move_project_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__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.move_project( - name='name_value', - destination_parent='destination_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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].destination_parent - mock_val = 'destination_parent_value' - assert arg == mock_val - - -def test_move_project_flattened_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.move_project( - projects.MoveProjectRequest(), - name='name_value', - destination_parent='destination_parent_value', - ) - -@pytest.mark.asyncio -async def test_move_project_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_project), - '__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.move_project( - name='name_value', - destination_parent='destination_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].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].destination_parent - mock_val = 'destination_parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_move_project_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.move_project( - projects.MoveProjectRequest(), - name='name_value', - destination_parent='destination_parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - projects.DeleteProjectRequest, - dict, -]) -def test_delete_project(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.DeleteProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - client.delete_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.DeleteProjectRequest() - -@pytest.mark.asyncio -async def test_delete_project_async(transport: str = 'grpc_asyncio', request_type=projects.DeleteProjectRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.DeleteProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_project_async_from_dict(): - await test_delete_project_async(request_type=dict) - - -def test_delete_project_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.DeleteProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_project_field_headers_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.DeleteProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_project_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_project( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_project_flattened_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_project( - projects.DeleteProjectRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_project_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_project( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_project_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_project( - projects.DeleteProjectRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - projects.UndeleteProjectRequest, - dict, -]) -def test_undelete_project(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undelete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UndeleteProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undelete_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__call__') as call: - client.undelete_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UndeleteProjectRequest() - -@pytest.mark.asyncio -async def test_undelete_project_async(transport: str = 'grpc_asyncio', request_type=projects.UndeleteProjectRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__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.undelete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UndeleteProjectRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undelete_project_async_from_dict(): - await test_undelete_project_async(request_type=dict) - - -def test_undelete_project_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.UndeleteProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undelete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_undelete_project_field_headers_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = projects.UndeleteProjectRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undelete_project(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_undelete_project_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__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.undelete_project( - 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_undelete_project_flattened_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undelete_project( - projects.UndeleteProjectRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_undelete_project_flattened_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_project), - '__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.undelete_project( - 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_undelete_project_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.undelete_project( - projects.UndeleteProjectRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = ProjectsClient( - 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() - - -def test_get_iam_policy_flattened(): - client = ProjectsClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = ProjectsClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = ProjectsAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = ProjectsClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = ProjectsClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = ProjectsAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = ProjectsClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = ProjectsClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = ProjectsAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - projects.GetProjectRequest, - dict, -]) -def test_get_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = projects.Project( - name='name_value', - parent='parent_value', - project_id='project_id_value', - state=projects.Project.State.ACTIVE, - display_name='display_name_value', - etag='etag_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = projects.Project.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_project(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, projects.Project) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.project_id == 'project_id_value' - assert response.state == projects.Project.State.ACTIVE - assert response.display_name == 'display_name_value' - assert response.etag == 'etag_value' - - -def test_get_project_rest_required_fields(request_type=projects.GetProjectRequest): - transport_class = transports.ProjectsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_project._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_project._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 = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = projects.Project() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = projects.Project.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_project(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_project_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_project._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProjectsRestInterceptor, "post_get_project") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_get_project") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.GetProjectRequest.pb(projects.GetProjectRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = projects.Project.to_json(projects.Project()) - - request = projects.GetProjectRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = projects.Project() - - client.get_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_project_rest_bad_request(transport: str = 'rest', request_type=projects.GetProjectRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_project(request) - - -def test_get_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = projects.Project() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = projects.Project.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_project(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=projects/*}" % client.transport._host, args[1]) - - -def test_get_project_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.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_project( - projects.GetProjectRequest(), - name='name_value', - ) - - -def test_get_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - projects.ListProjectsRequest, - dict, -]) -def test_list_projects_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = projects.ListProjectsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = projects.ListProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_projects(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProjectsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_projects_rest_required_fields(request_type=projects.ListProjectsRequest): - transport_class = transports.ProjectsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "parent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_projects._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "parent" in jsonified_request - assert jsonified_request["parent"] == request_init["parent"] - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_projects._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "parent", "show_deleted", )) - 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 = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = projects.ListProjectsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = projects.ListProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_projects(request) - - expected_params = [ - ( - "parent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_projects_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_projects._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", "showDeleted", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_projects_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProjectsRestInterceptor, "post_list_projects") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_list_projects") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.ListProjectsRequest.pb(projects.ListProjectsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = projects.ListProjectsResponse.to_json(projects.ListProjectsResponse()) - - request = projects.ListProjectsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = projects.ListProjectsResponse() - - client.list_projects(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_projects_rest_bad_request(transport: str = 'rest', request_type=projects.ListProjectsRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_projects(request) - - -def test_list_projects_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = projects.ListProjectsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = projects.ListProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_projects(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/projects" % client.transport._host, args[1]) - - -def test_list_projects_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.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_projects( - projects.ListProjectsRequest(), - parent='parent_value', - ) - - -def test_list_projects_rest_pager(transport: str = 'rest'): - client = ProjectsClient( - 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 = ( - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.ListProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.ListProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(projects.ListProjectsResponse.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 = {} - - pager = client.list_projects(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, projects.Project) - for i in results) - - pages = list(client.list_projects(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - projects.SearchProjectsRequest, - dict, -]) -def test_search_projects_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = projects.SearchProjectsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = projects.SearchProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_projects(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchProjectsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_projects_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProjectsRestInterceptor, "post_search_projects") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_search_projects") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.SearchProjectsRequest.pb(projects.SearchProjectsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = projects.SearchProjectsResponse.to_json(projects.SearchProjectsResponse()) - - request = projects.SearchProjectsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = projects.SearchProjectsResponse() - - client.search_projects(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_projects_rest_bad_request(transport: str = 'rest', request_type=projects.SearchProjectsRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search_projects(request) - - -def test_search_projects_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = projects.SearchProjectsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - query='query_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = projects.SearchProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_projects(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/projects:search" % client.transport._host, args[1]) - - -def test_search_projects_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_projects( - projects.SearchProjectsRequest(), - query='query_value', - ) - - -def test_search_projects_rest_pager(transport: str = 'rest'): - client = ProjectsClient( - 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 = ( - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - projects.Project(), - ], - next_page_token='abc', - ), - projects.SearchProjectsResponse( - projects=[], - next_page_token='def', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - ], - next_page_token='ghi', - ), - projects.SearchProjectsResponse( - projects=[ - projects.Project(), - projects.Project(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(projects.SearchProjectsResponse.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 = {} - - pager = client.search_projects(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, projects.Project) - for i in results) - - pages = list(client.search_projects(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - projects.CreateProjectRequest, - dict, -]) -def test_create_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["project"] = {'name': 'name_value', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_project_rest_required_fields(request_type=projects.CreateProjectRequest): - transport_class = transports.ProjectsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_project._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()).create_project._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ProjectsClient( - 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_project(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_project_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_project._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("project", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_create_project") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_create_project") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.CreateProjectRequest.pb(projects.CreateProjectRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = projects.CreateProjectRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_project_rest_bad_request(transport: str = 'rest', request_type=projects.CreateProjectRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["project"] = {'name': 'name_value', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_project(request) - - -def test_create_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {} - - # get truthy value for each flattened field - mock_args = dict( - project=projects.Project(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_project(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/projects" % client.transport._host, args[1]) - - -def test_create_project_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.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_project( - projects.CreateProjectRequest(), - project=projects.Project(name='name_value'), - ) - - -def test_create_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - projects.UpdateProjectRequest, - dict, -]) -def test_update_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'project': {'name': 'projects/sample1'}} - request_init["project"] = {'name': 'projects/sample1', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_project_rest_required_fields(request_type=projects.UpdateProjectRequest): - transport_class = transports.ProjectsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_project._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_project._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 = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_project(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_project_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_project._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("project", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_update_project") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_update_project") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.UpdateProjectRequest.pb(projects.UpdateProjectRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = projects.UpdateProjectRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_project_rest_bad_request(transport: str = 'rest', request_type=projects.UpdateProjectRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'project': {'name': 'projects/sample1'}} - request_init["project"] = {'name': 'projects/sample1', 'parent': 'parent_value', 'project_id': 'project_id_value', 'state': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_project(request) - - -def test_update_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {'project': {'name': 'projects/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - project=projects.Project(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_project(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{project.name=projects/*}" % client.transport._host, args[1]) - - -def test_update_project_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.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_project( - projects.UpdateProjectRequest(), - project=projects.Project(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - projects.MoveProjectRequest, - dict, -]) -def test_move_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.move_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_move_project_rest_required_fields(request_type=projects.MoveProjectRequest): - transport_class = transports.ProjectsRestTransport - - request_init = {} - request_init["name"] = "" - request_init["destination_parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_project._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["destinationParent"] = 'destination_parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).move_project._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 "destinationParent" in jsonified_request - assert jsonified_request["destinationParent"] == 'destination_parent_value' - - client = ProjectsClient( - 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.move_project(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_move_project_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.move_project._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "destinationParent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_move_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_move_project") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_move_project") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.MoveProjectRequest.pb(projects.MoveProjectRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = projects.MoveProjectRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.move_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_move_project_rest_bad_request(transport: str = 'rest', request_type=projects.MoveProjectRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.move_project(request) - - -def test_move_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - destination_parent='destination_parent_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.move_project(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=projects/*}:move" % client.transport._host, args[1]) - - -def test_move_project_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.move_project( - projects.MoveProjectRequest(), - name='name_value', - destination_parent='destination_parent_value', - ) - - -def test_move_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - projects.DeleteProjectRequest, - dict, -]) -def test_delete_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_project_rest_required_fields(request_type=projects.DeleteProjectRequest): - transport_class = transports.ProjectsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_project._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_project._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 = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_project(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_project_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_project._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_delete_project") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_delete_project") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.DeleteProjectRequest.pb(projects.DeleteProjectRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = projects.DeleteProjectRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_project_rest_bad_request(transport: str = 'rest', request_type=projects.DeleteProjectRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_project(request) - - -def test_delete_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_project(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=projects/*}" % client.transport._host, args[1]) - - -def test_delete_project_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_project( - projects.DeleteProjectRequest(), - name='name_value', - ) - - -def test_delete_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - projects.UndeleteProjectRequest, - dict, -]) -def test_undelete_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.undelete_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_undelete_project_rest_required_fields(request_type=projects.UndeleteProjectRequest): - transport_class = transports.ProjectsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undelete_project._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()).undelete_project._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 = ProjectsClient( - 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.undelete_project(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undelete_project_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undelete_project._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_undelete_project") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_undelete_project") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.UndeleteProjectRequest.pb(projects.UndeleteProjectRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = projects.UndeleteProjectRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undelete_project(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undelete_project_rest_bad_request(transport: str = 'rest', request_type=projects.UndeleteProjectRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.undelete_project(request) - - -def test_undelete_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.undelete_project(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=projects/*}:undelete" % client.transport._host, args[1]) - - -def test_undelete_project_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.undelete_project( - projects.UndeleteProjectRequest(), - name='name_value', - ) - - -def test_undelete_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': '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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.ProjectsRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProjectsRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=projects/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': '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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.ProjectsRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProjectsRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=projects/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': '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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.ProjectsRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.ProjectsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProjectsRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.ProjectsRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': '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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=projects/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProjectsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProjectsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProjectsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProjectsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProjectsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProjectsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProjectsGrpcTransport, - transports.ProjectsGrpcAsyncIOTransport, - transports.ProjectsRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ProjectsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProjectsGrpcTransport, - ) - -def test_projects_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProjectsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_projects_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.resourcemanager_v3.services.projects.transports.ProjectsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProjectsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_project', - 'list_projects', - 'search_projects', - 'create_project', - 'update_project', - 'move_project', - 'delete_project', - 'undelete_project', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - 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_projects_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.resourcemanager_v3.services.projects.transports.ProjectsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProjectsTransport( - 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/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -def test_projects_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.resourcemanager_v3.services.projects.transports.ProjectsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProjectsTransport() - adc.assert_called_once() - - -def test_projects_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) - ProjectsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProjectsGrpcTransport, - transports.ProjectsGrpcAsyncIOTransport, - ], -) -def test_projects_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/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProjectsGrpcTransport, - transports.ProjectsGrpcAsyncIOTransport, - transports.ProjectsRestTransport, - ], -) -def test_projects_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.ProjectsGrpcTransport, grpc_helpers), - (transports.ProjectsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_projects_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( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProjectsGrpcTransport, transports.ProjectsGrpcAsyncIOTransport]) -def test_projects_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_projects_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.ProjectsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_projects_rest_lro_client(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_projects_host_no_port(transport_name): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_projects_host_with_port(transport_name): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_projects_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ProjectsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ProjectsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_project._session - session2 = client2.transport.get_project._session - assert session1 != session2 - session1 = client1.transport.list_projects._session - session2 = client2.transport.list_projects._session - assert session1 != session2 - session1 = client1.transport.search_projects._session - session2 = client2.transport.search_projects._session - assert session1 != session2 - session1 = client1.transport.create_project._session - session2 = client2.transport.create_project._session - assert session1 != session2 - session1 = client1.transport.update_project._session - session2 = client2.transport.update_project._session - assert session1 != session2 - session1 = client1.transport.move_project._session - session2 = client2.transport.move_project._session - assert session1 != session2 - session1 = client1.transport.delete_project._session - session2 = client2.transport.delete_project._session - assert session1 != session2 - session1 = client1.transport.undelete_project._session - session2 = client2.transport.undelete_project._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 -def test_projects_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProjectsGrpcTransport( - 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_projects_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProjectsGrpcAsyncIOTransport( - 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.ProjectsGrpcTransport, transports.ProjectsGrpcAsyncIOTransport]) -def test_projects_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.ProjectsGrpcTransport, transports.ProjectsGrpcAsyncIOTransport]) -def test_projects_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_projects_grpc_lro_client(): - client = ProjectsClient( - 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_projects_grpc_lro_async_client(): - client = ProjectsAsyncClient( - 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_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProjectsClient.project_path(project) - assert expected == actual - - -def test_parse_project_path(): - expected = { - "project": "clam", - } - path = ProjectsClient.project_path(**expected) - - # Check that the path construction is reversible. - actual = ProjectsClient.parse_project_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProjectsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ProjectsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProjectsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProjectsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ProjectsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProjectsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProjectsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ProjectsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProjectsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ProjectsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ProjectsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProjectsClient.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 = ProjectsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ProjectsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProjectsClient.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.ProjectsTransport, '_prep_wrapped_messages') as prep: - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProjectsTransport, '_prep_wrapped_messages') as prep: - transport_class = ProjectsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ProjectsClient( - 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", [ - (ProjectsClient, transports.ProjectsGrpcTransport), - (ProjectsAsyncClient, transports.ProjectsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py deleted file mode 100644 index f71883f..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py +++ /dev/null @@ -1,2788 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.resourcemanager_v3.services.tag_bindings import TagBindingsAsyncClient -from google.cloud.resourcemanager_v3.services.tag_bindings import TagBindingsClient -from google.cloud.resourcemanager_v3.services.tag_bindings import pagers -from google.cloud.resourcemanager_v3.services.tag_bindings import transports -from google.cloud.resourcemanager_v3.types import tag_bindings -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert TagBindingsClient._get_default_mtls_endpoint(None) is None - assert TagBindingsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TagBindingsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TagBindingsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TagBindingsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TagBindingsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (TagBindingsClient, "grpc"), - (TagBindingsAsyncClient, "grpc_asyncio"), - (TagBindingsClient, "rest"), -]) -def test_tag_bindings_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.TagBindingsGrpcTransport, "grpc"), - (transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TagBindingsRestTransport, "rest"), -]) -def test_tag_bindings_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", [ - (TagBindingsClient, "grpc"), - (TagBindingsAsyncClient, "grpc_asyncio"), - (TagBindingsClient, "rest"), -]) -def test_tag_bindings_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -def test_tag_bindings_client_get_transport_class(): - transport = TagBindingsClient.get_transport_class() - available_transports = [ - transports.TagBindingsGrpcTransport, - transports.TagBindingsRestTransport, - ] - assert transport in available_transports - - transport = TagBindingsClient.get_transport_class("grpc") - assert transport == transports.TagBindingsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc"), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio"), - (TagBindingsClient, transports.TagBindingsRestTransport, "rest"), -]) -@mock.patch.object(TagBindingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsClient)) -@mock.patch.object(TagBindingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsAsyncClient)) -def test_tag_bindings_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(TagBindingsClient, '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(TagBindingsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", "true"), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", "false"), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TagBindingsClient, transports.TagBindingsRestTransport, "rest", "true"), - (TagBindingsClient, transports.TagBindingsRestTransport, "rest", "false"), -]) -@mock.patch.object(TagBindingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsClient)) -@mock.patch.object(TagBindingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_tag_bindings_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - TagBindingsClient, TagBindingsAsyncClient -]) -@mock.patch.object(TagBindingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsClient)) -@mock.patch.object(TagBindingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagBindingsAsyncClient)) -def test_tag_bindings_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc"), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio"), - (TagBindingsClient, transports.TagBindingsRestTransport, "rest"), -]) -def test_tag_bindings_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", grpc_helpers), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TagBindingsClient, transports.TagBindingsRestTransport, "rest", None), -]) -def test_tag_bindings_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_tag_bindings_client_client_options_from_dict(): - with mock.patch('google.cloud.resourcemanager_v3.services.tag_bindings.transports.TagBindingsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TagBindingsClient( - 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", [ - (TagBindingsClient, transports.TagBindingsGrpcTransport, "grpc", grpc_helpers), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_tag_bindings_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=None, - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - tag_bindings.ListTagBindingsRequest, - dict, -]) -def test_list_tag_bindings(request_type, transport: str = 'grpc'): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_bindings.ListTagBindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tag_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListTagBindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagBindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tag_bindings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), - '__call__') as call: - client.list_tag_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListTagBindingsRequest() - -@pytest.mark.asyncio -async def test_list_tag_bindings_async(transport: str = 'grpc_asyncio', request_type=tag_bindings.ListTagBindingsRequest): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_bindings.ListTagBindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tag_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListTagBindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagBindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tag_bindings_async_from_dict(): - await test_list_tag_bindings_async(request_type=dict) - - -def test_list_tag_bindings_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_bindings.ListTagBindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tag_bindings( - 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_tag_bindings_flattened_error(): - client = TagBindingsClient( - credentials=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_tag_bindings( - tag_bindings.ListTagBindingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tag_bindings_flattened_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_bindings.ListTagBindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_bindings.ListTagBindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tag_bindings( - 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_tag_bindings_flattened_error_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_tag_bindings( - tag_bindings.ListTagBindingsRequest(), - parent='parent_value', - ) - - -def test_list_tag_bindings_pager(transport_name: str = "grpc"): - client = TagBindingsClient( - 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_tag_bindings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - next_page_token='abc', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[], - next_page_token='def', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - ], - next_page_token='ghi', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_tag_bindings(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_bindings.TagBinding) - for i in results) -def test_list_tag_bindings_pages(transport_name: str = "grpc"): - client = TagBindingsClient( - 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_tag_bindings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - next_page_token='abc', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[], - next_page_token='def', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - ], - next_page_token='ghi', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tag_bindings(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_tag_bindings_async_pager(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - next_page_token='abc', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[], - next_page_token='def', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - ], - next_page_token='ghi', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tag_bindings(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, tag_bindings.TagBinding) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tag_bindings_async_pages(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - next_page_token='abc', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[], - next_page_token='def', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - ], - next_page_token='ghi', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_tag_bindings(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - tag_bindings.CreateTagBindingRequest, - dict, -]) -def test_create_tag_binding(request_type, transport: str = 'grpc'): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_tag_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.CreateTagBindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_tag_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_binding), - '__call__') as call: - client.create_tag_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.CreateTagBindingRequest() - -@pytest.mark.asyncio -async def test_create_tag_binding_async(transport: str = 'grpc_asyncio', request_type=tag_bindings.CreateTagBindingRequest): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_binding), - '__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_tag_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.CreateTagBindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_tag_binding_async_from_dict(): - await test_create_tag_binding_async(request_type=dict) - - -def test_create_tag_binding_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_binding), - '__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_tag_binding( - tag_binding=tag_bindings.TagBinding(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].tag_binding - mock_val = tag_bindings.TagBinding(name='name_value') - assert arg == mock_val - - -def test_create_tag_binding_flattened_error(): - client = TagBindingsClient( - credentials=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_tag_binding( - tag_bindings.CreateTagBindingRequest(), - tag_binding=tag_bindings.TagBinding(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_tag_binding_flattened_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_binding), - '__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_tag_binding( - tag_binding=tag_bindings.TagBinding(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].tag_binding - mock_val = tag_bindings.TagBinding(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_tag_binding_flattened_error_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_tag_binding( - tag_bindings.CreateTagBindingRequest(), - tag_binding=tag_bindings.TagBinding(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - tag_bindings.DeleteTagBindingRequest, - dict, -]) -def test_delete_tag_binding(request_type, transport: str = 'grpc'): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_tag_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.DeleteTagBindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_tag_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - client.delete_tag_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.DeleteTagBindingRequest() - -@pytest.mark.asyncio -async def test_delete_tag_binding_async(transport: str = 'grpc_asyncio', request_type=tag_bindings.DeleteTagBindingRequest): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_tag_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.DeleteTagBindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_tag_binding_async_from_dict(): - await test_delete_tag_binding_async(request_type=dict) - - -def test_delete_tag_binding_field_headers(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_bindings.DeleteTagBindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_tag_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_tag_binding_field_headers_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_bindings.DeleteTagBindingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_tag_binding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_tag_binding_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_tag_binding( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_tag_binding_flattened_error(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_tag_binding( - tag_bindings.DeleteTagBindingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_tag_binding_flattened_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_tag_binding( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_tag_binding_flattened_error_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_tag_binding( - tag_bindings.DeleteTagBindingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - tag_bindings.ListTagBindingsRequest, - dict, -]) -def test_list_tag_bindings_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_bindings.ListTagBindingsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tag_bindings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagBindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tag_bindings_rest_required_fields(request_type=tag_bindings.ListTagBindingsRequest): - transport_class = transports.TagBindingsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "parent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_bindings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "parent" in jsonified_request - assert jsonified_request["parent"] == request_init["parent"] - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_bindings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "parent", )) - 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 = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tag_bindings.ListTagBindingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tag_bindings(request) - - expected_params = [ - ( - "parent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tag_bindings_rest_unset_required_fields(): - transport = transports.TagBindingsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tag_bindings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_bindings_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagBindingsRestInterceptor, "post_list_tag_bindings") as post, \ - mock.patch.object(transports.TagBindingsRestInterceptor, "pre_list_tag_bindings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.ListTagBindingsRequest.pb(tag_bindings.ListTagBindingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tag_bindings.ListTagBindingsResponse.to_json(tag_bindings.ListTagBindingsResponse()) - - request = tag_bindings.ListTagBindingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_bindings.ListTagBindingsResponse() - - client.list_tag_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_bindings_rest_bad_request(transport: str = 'rest', request_type=tag_bindings.ListTagBindingsRequest): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_tag_bindings(request) - - -def test_list_tag_bindings_rest_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_bindings.ListTagBindingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tag_bindings(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/tagBindings" % client.transport._host, args[1]) - - -def test_list_tag_bindings_rest_flattened_error(transport: str = 'rest'): - client = TagBindingsClient( - credentials=ga_credentials.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_tag_bindings( - tag_bindings.ListTagBindingsRequest(), - parent='parent_value', - ) - - -def test_list_tag_bindings_rest_pager(transport: str = 'rest'): - client = TagBindingsClient( - 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 = ( - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - next_page_token='abc', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[], - next_page_token='def', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - ], - next_page_token='ghi', - ), - tag_bindings.ListTagBindingsResponse( - tag_bindings=[ - tag_bindings.TagBinding(), - tag_bindings.TagBinding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(tag_bindings.ListTagBindingsResponse.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 = {} - - pager = client.list_tag_bindings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_bindings.TagBinding) - for i in results) - - pages = list(client.list_tag_bindings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - tag_bindings.CreateTagBindingRequest, - dict, -]) -def test_create_tag_binding_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_binding"] = {'name': 'name_value', 'parent': 'parent_value', 'tag_value': 'tag_value_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_tag_binding(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_tag_binding_rest_required_fields(request_type=tag_bindings.CreateTagBindingRequest): - transport_class = transports.TagBindingsRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tag_binding._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()).create_tag_binding._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = TagBindingsClient( - 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_tag_binding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_tag_binding_rest_unset_required_fields(): - transport = transports.TagBindingsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_tag_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", )) & set(("tagBinding", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_binding_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_create_tag_binding") as post, \ - mock.patch.object(transports.TagBindingsRestInterceptor, "pre_create_tag_binding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.CreateTagBindingRequest.pb(tag_bindings.CreateTagBindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_bindings.CreateTagBindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_binding_rest_bad_request(transport: str = 'rest', request_type=tag_bindings.CreateTagBindingRequest): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_binding"] = {'name': 'name_value', 'parent': 'parent_value', 'tag_value': 'tag_value_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_tag_binding(request) - - -def test_create_tag_binding_rest_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {} - - # get truthy value for each flattened field - mock_args = dict( - tag_binding=tag_bindings.TagBinding(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_tag_binding(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/tagBindings" % client.transport._host, args[1]) - - -def test_create_tag_binding_rest_flattened_error(transport: str = 'rest'): - client = TagBindingsClient( - credentials=ga_credentials.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_tag_binding( - tag_bindings.CreateTagBindingRequest(), - tag_binding=tag_bindings.TagBinding(name='name_value'), - ) - - -def test_create_tag_binding_rest_error(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_bindings.DeleteTagBindingRequest, - dict, -]) -def test_delete_tag_binding_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagBindings/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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_tag_binding(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_tag_binding_rest_required_fields(request_type=tag_bindings.DeleteTagBindingRequest): - transport_class = transports.TagBindingsRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_binding._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_binding._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 = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_tag_binding(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_tag_binding_rest_unset_required_fields(): - transport = transports.TagBindingsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_tag_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_binding_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_delete_tag_binding") as post, \ - mock.patch.object(transports.TagBindingsRestInterceptor, "pre_delete_tag_binding") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.DeleteTagBindingRequest.pb(tag_bindings.DeleteTagBindingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_bindings.DeleteTagBindingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_binding_rest_bad_request(transport: str = 'rest', request_type=tag_bindings.DeleteTagBindingRequest): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagBindings/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_tag_binding(request) - - -def test_delete_tag_binding_rest_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'tagBindings/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_tag_binding(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=tagBindings/**}" % client.transport._host, args[1]) - - -def test_delete_tag_binding_rest_flattened_error(transport: str = 'rest'): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_tag_binding( - tag_bindings.DeleteTagBindingRequest(), - name='name_value', - ) - - -def test_delete_tag_binding_rest_error(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TagBindingsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TagBindingsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TagBindingsGrpcTransport, - transports.TagBindingsGrpcAsyncIOTransport, - transports.TagBindingsRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = TagBindingsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TagBindingsGrpcTransport, - ) - -def test_tag_bindings_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TagBindingsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_tag_bindings_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.resourcemanager_v3.services.tag_bindings.transports.TagBindingsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TagBindingsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_tag_bindings', - 'create_tag_binding', - 'delete_tag_binding', - ) - 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_tag_bindings_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.resourcemanager_v3.services.tag_bindings.transports.TagBindingsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TagBindingsTransport( - 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/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -def test_tag_bindings_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.resourcemanager_v3.services.tag_bindings.transports.TagBindingsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TagBindingsTransport() - adc.assert_called_once() - - -def test_tag_bindings_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) - TagBindingsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagBindingsGrpcTransport, - transports.TagBindingsGrpcAsyncIOTransport, - ], -) -def test_tag_bindings_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/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagBindingsGrpcTransport, - transports.TagBindingsGrpcAsyncIOTransport, - transports.TagBindingsRestTransport, - ], -) -def test_tag_bindings_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.TagBindingsGrpcTransport, grpc_helpers), - (transports.TagBindingsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_tag_bindings_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( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TagBindingsGrpcTransport, transports.TagBindingsGrpcAsyncIOTransport]) -def test_tag_bindings_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_tag_bindings_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.TagBindingsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_tag_bindings_rest_lro_client(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_tag_bindings_host_no_port(transport_name): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_tag_bindings_host_with_port(transport_name): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_tag_bindings_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = TagBindingsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = TagBindingsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_tag_bindings._session - session2 = client2.transport.list_tag_bindings._session - assert session1 != session2 - session1 = client1.transport.create_tag_binding._session - session2 = client2.transport.create_tag_binding._session - assert session1 != session2 - session1 = client1.transport.delete_tag_binding._session - session2 = client2.transport.delete_tag_binding._session - assert session1 != session2 -def test_tag_bindings_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TagBindingsGrpcTransport( - 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_tag_bindings_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TagBindingsGrpcAsyncIOTransport( - 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.TagBindingsGrpcTransport, transports.TagBindingsGrpcAsyncIOTransport]) -def test_tag_bindings_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.TagBindingsGrpcTransport, transports.TagBindingsGrpcAsyncIOTransport]) -def test_tag_bindings_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_tag_bindings_grpc_lro_client(): - client = TagBindingsClient( - 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_tag_bindings_grpc_lro_async_client(): - client = TagBindingsAsyncClient( - 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_tag_binding_path(): - tag_binding = "squid" - expected = "tagBindings/{tag_binding}".format(tag_binding=tag_binding, ) - actual = TagBindingsClient.tag_binding_path(tag_binding) - assert expected == actual - - -def test_parse_tag_binding_path(): - expected = { - "tag_binding": "clam", - } - path = TagBindingsClient.tag_binding_path(**expected) - - # Check that the path construction is reversible. - actual = TagBindingsClient.parse_tag_binding_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TagBindingsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = TagBindingsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TagBindingsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = TagBindingsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = TagBindingsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TagBindingsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TagBindingsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = TagBindingsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TagBindingsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = TagBindingsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = TagBindingsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TagBindingsClient.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 = TagBindingsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = TagBindingsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TagBindingsClient.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.TagBindingsTransport, '_prep_wrapped_messages') as prep: - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TagBindingsTransport, '_prep_wrapped_messages') as prep: - transport_class = TagBindingsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = TagBindingsClient( - 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", [ - (TagBindingsClient, transports.TagBindingsGrpcTransport), - (TagBindingsAsyncClient, transports.TagBindingsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py deleted file mode 100644 index 83be7f1..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py +++ /dev/null @@ -1,5257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.resourcemanager_v3.services.tag_keys import TagKeysAsyncClient -from google.cloud.resourcemanager_v3.services.tag_keys import TagKeysClient -from google.cloud.resourcemanager_v3.services.tag_keys import pagers -from google.cloud.resourcemanager_v3.services.tag_keys import transports -from google.cloud.resourcemanager_v3.types import tag_keys -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 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert TagKeysClient._get_default_mtls_endpoint(None) is None - assert TagKeysClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TagKeysClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TagKeysClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TagKeysClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TagKeysClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (TagKeysClient, "grpc"), - (TagKeysAsyncClient, "grpc_asyncio"), - (TagKeysClient, "rest"), -]) -def test_tag_keys_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.TagKeysGrpcTransport, "grpc"), - (transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TagKeysRestTransport, "rest"), -]) -def test_tag_keys_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", [ - (TagKeysClient, "grpc"), - (TagKeysAsyncClient, "grpc_asyncio"), - (TagKeysClient, "rest"), -]) -def test_tag_keys_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -def test_tag_keys_client_get_transport_class(): - transport = TagKeysClient.get_transport_class() - available_transports = [ - transports.TagKeysGrpcTransport, - transports.TagKeysRestTransport, - ] - assert transport in available_transports - - transport = TagKeysClient.get_transport_class("grpc") - assert transport == transports.TagKeysGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TagKeysClient, transports.TagKeysGrpcTransport, "grpc"), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio"), - (TagKeysClient, transports.TagKeysRestTransport, "rest"), -]) -@mock.patch.object(TagKeysClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysClient)) -@mock.patch.object(TagKeysAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysAsyncClient)) -def test_tag_keys_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(TagKeysClient, '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(TagKeysClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", "true"), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", "false"), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TagKeysClient, transports.TagKeysRestTransport, "rest", "true"), - (TagKeysClient, transports.TagKeysRestTransport, "rest", "false"), -]) -@mock.patch.object(TagKeysClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysClient)) -@mock.patch.object(TagKeysAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_tag_keys_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - TagKeysClient, TagKeysAsyncClient -]) -@mock.patch.object(TagKeysClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysClient)) -@mock.patch.object(TagKeysAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagKeysAsyncClient)) -def test_tag_keys_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TagKeysClient, transports.TagKeysGrpcTransport, "grpc"), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio"), - (TagKeysClient, transports.TagKeysRestTransport, "rest"), -]) -def test_tag_keys_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", grpc_helpers), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TagKeysClient, transports.TagKeysRestTransport, "rest", None), -]) -def test_tag_keys_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_tag_keys_client_client_options_from_dict(): - with mock.patch('google.cloud.resourcemanager_v3.services.tag_keys.transports.TagKeysGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TagKeysClient( - 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", [ - (TagKeysClient, transports.TagKeysGrpcTransport, "grpc", grpc_helpers), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_tag_keys_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=None, - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.ListTagKeysRequest, - dict, -]) -def test_list_tag_keys(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_keys.ListTagKeysResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tag_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] == tag_keys.ListTagKeysRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagKeysPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tag_keys_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_keys), - '__call__') as call: - client.list_tag_keys() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.ListTagKeysRequest() - -@pytest.mark.asyncio -async def test_list_tag_keys_async(transport: str = 'grpc_asyncio', request_type=tag_keys.ListTagKeysRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.ListTagKeysResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tag_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.ListTagKeysRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagKeysAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tag_keys_async_from_dict(): - await test_list_tag_keys_async(request_type=dict) - - -def test_list_tag_keys_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_keys.ListTagKeysResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tag_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_tag_keys_flattened_error(): - client = TagKeysClient( - credentials=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_tag_keys( - tag_keys.ListTagKeysRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tag_keys_flattened_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_keys.ListTagKeysResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.ListTagKeysResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tag_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_tag_keys_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_tag_keys( - tag_keys.ListTagKeysRequest(), - parent='parent_value', - ) - - -def test_list_tag_keys_pager(transport_name: str = "grpc"): - client = TagKeysClient( - 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_tag_keys), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - next_page_token='abc', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[], - next_page_token='def', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - ], - next_page_token='ghi', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_tag_keys(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_keys.TagKey) - for i in results) -def test_list_tag_keys_pages(transport_name: str = "grpc"): - client = TagKeysClient( - 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_tag_keys), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - next_page_token='abc', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[], - next_page_token='def', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - ], - next_page_token='ghi', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tag_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_tag_keys_async_pager(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_keys), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - next_page_token='abc', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[], - next_page_token='def', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - ], - next_page_token='ghi', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tag_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, tag_keys.TagKey) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tag_keys_async_pages(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_keys), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - next_page_token='abc', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[], - next_page_token='def', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - ], - next_page_token='ghi', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_tag_keys(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - tag_keys.GetTagKeyRequest, - dict, -]) -def test_get_tag_key(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_keys.TagKey( - name='name_value', - parent='parent_value', - short_name='short_name_value', - namespaced_name='namespaced_name_value', - description='description_value', - etag='etag_value', - ) - response = client.get_tag_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] == tag_keys.GetTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_keys.TagKey) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.short_name == 'short_name_value' - assert response.namespaced_name == 'namespaced_name_value' - assert response.description == 'description_value' - assert response.etag == 'etag_value' - - -def test_get_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_key), - '__call__') as call: - client.get_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.GetTagKeyRequest() - -@pytest.mark.asyncio -async def test_get_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.GetTagKeyRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.TagKey( - name='name_value', - parent='parent_value', - short_name='short_name_value', - namespaced_name='namespaced_name_value', - description='description_value', - etag='etag_value', - )) - response = await client.get_tag_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.GetTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_keys.TagKey) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.short_name == 'short_name_value' - assert response.namespaced_name == 'namespaced_name_value' - assert response.description == 'description_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_tag_key_async_from_dict(): - await test_get_tag_key_async(request_type=dict) - - -def test_get_tag_key_field_headers(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_keys.GetTagKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_key), - '__call__') as call: - call.return_value = tag_keys.TagKey() - client.get_tag_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_tag_key_field_headers_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_keys.GetTagKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.TagKey()) - await client.get_tag_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_tag_key_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_keys.TagKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_tag_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_tag_key_flattened_error(): - client = TagKeysClient( - credentials=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_tag_key( - tag_keys.GetTagKeyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_tag_key_flattened_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_keys.TagKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_keys.TagKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_tag_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_tag_key_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_tag_key( - tag_keys.GetTagKeyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.CreateTagKeyRequest, - dict, -]) -def test_create_tag_key(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_tag_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] == tag_keys.CreateTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_key), - '__call__') as call: - client.create_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.CreateTagKeyRequest() - -@pytest.mark.asyncio -async def test_create_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.CreateTagKeyRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_key), - '__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_tag_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.CreateTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_tag_key_async_from_dict(): - await test_create_tag_key_async(request_type=dict) - - -def test_create_tag_key_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_key), - '__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_tag_key( - tag_key=tag_keys.TagKey(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].tag_key - mock_val = tag_keys.TagKey(name='name_value') - assert arg == mock_val - - -def test_create_tag_key_flattened_error(): - client = TagKeysClient( - credentials=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_tag_key( - tag_keys.CreateTagKeyRequest(), - tag_key=tag_keys.TagKey(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_tag_key_flattened_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_key), - '__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_tag_key( - tag_key=tag_keys.TagKey(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].tag_key - mock_val = tag_keys.TagKey(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_tag_key_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_tag_key( - tag_keys.CreateTagKeyRequest(), - tag_key=tag_keys.TagKey(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.UpdateTagKeyRequest, - dict, -]) -def test_update_tag_key(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_tag_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] == tag_keys.UpdateTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_key), - '__call__') as call: - client.update_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.UpdateTagKeyRequest() - -@pytest.mark.asyncio -async def test_update_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.UpdateTagKeyRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_tag_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.UpdateTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_tag_key_async_from_dict(): - await test_update_tag_key_async(request_type=dict) - - -def test_update_tag_key_field_headers(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_keys.UpdateTagKeyRequest() - - request.tag_key.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_key), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_tag_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', - 'tag_key.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tag_key_field_headers_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_keys.UpdateTagKeyRequest() - - request.tag_key.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_tag_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', - 'tag_key.name=name_value', - ) in kw['metadata'] - - -def test_update_tag_key_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag_key( - tag_key=tag_keys.TagKey(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].tag_key - mock_val = tag_keys.TagKey(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_tag_key_flattened_error(): - client = TagKeysClient( - credentials=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_tag_key( - tag_keys.UpdateTagKeyRequest(), - tag_key=tag_keys.TagKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_tag_key_flattened_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag_key( - tag_key=tag_keys.TagKey(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].tag_key - mock_val = tag_keys.TagKey(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_tag_key_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_tag_key( - tag_keys.UpdateTagKeyRequest(), - tag_key=tag_keys.TagKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.DeleteTagKeyRequest, - dict, -]) -def test_delete_tag_key(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_tag_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] == tag_keys.DeleteTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - client.delete_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.DeleteTagKeyRequest() - -@pytest.mark.asyncio -async def test_delete_tag_key_async(transport: str = 'grpc_asyncio', request_type=tag_keys.DeleteTagKeyRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_tag_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.DeleteTagKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_tag_key_async_from_dict(): - await test_delete_tag_key_async(request_type=dict) - - -def test_delete_tag_key_field_headers(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_keys.DeleteTagKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_tag_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_delete_tag_key_field_headers_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_keys.DeleteTagKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_tag_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_delete_tag_key_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_tag_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_delete_tag_key_flattened_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_tag_key( - tag_keys.DeleteTagKeyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_tag_key_flattened_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_tag_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_delete_tag_key_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_tag_key( - tag_keys.DeleteTagKeyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = TagKeysClient( - 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() - - -def test_get_iam_policy_flattened(): - client = TagKeysClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = TagKeysClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = TagKeysAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = TagKeysClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = TagKeysClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = TagKeysAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = TagKeysClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = TagKeysClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = TagKeysAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.ListTagKeysRequest, - dict, -]) -def test_list_tag_keys_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_keys.ListTagKeysResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_keys.ListTagKeysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tag_keys(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagKeysPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tag_keys_rest_required_fields(request_type=tag_keys.ListTagKeysRequest): - transport_class = transports.TagKeysRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "parent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_keys._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "parent" in jsonified_request - assert jsonified_request["parent"] == request_init["parent"] - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_keys._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "parent", )) - 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 = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tag_keys.ListTagKeysResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = tag_keys.ListTagKeysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tag_keys(request) - - expected_params = [ - ( - "parent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tag_keys_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tag_keys._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_keys_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagKeysRestInterceptor, "post_list_tag_keys") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_list_tag_keys") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.ListTagKeysRequest.pb(tag_keys.ListTagKeysRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tag_keys.ListTagKeysResponse.to_json(tag_keys.ListTagKeysResponse()) - - request = tag_keys.ListTagKeysRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_keys.ListTagKeysResponse() - - client.list_tag_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_keys_rest_bad_request(transport: str = 'rest', request_type=tag_keys.ListTagKeysRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_tag_keys(request) - - -def test_list_tag_keys_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_keys.ListTagKeysResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_keys.ListTagKeysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tag_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/v3/tagKeys" % client.transport._host, args[1]) - - -def test_list_tag_keys_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.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_tag_keys( - tag_keys.ListTagKeysRequest(), - parent='parent_value', - ) - - -def test_list_tag_keys_rest_pager(transport: str = 'rest'): - client = TagKeysClient( - 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 = ( - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - next_page_token='abc', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[], - next_page_token='def', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - ], - next_page_token='ghi', - ), - tag_keys.ListTagKeysResponse( - tag_keys=[ - tag_keys.TagKey(), - tag_keys.TagKey(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(tag_keys.ListTagKeysResponse.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 = {} - - pager = client.list_tag_keys(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_keys.TagKey) - for i in results) - - pages = list(client.list_tag_keys(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - tag_keys.GetTagKeyRequest, - dict, -]) -def test_get_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagKeys/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 = tag_keys.TagKey( - name='name_value', - parent='parent_value', - short_name='short_name_value', - namespaced_name='namespaced_name_value', - description='description_value', - etag='etag_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_keys.TagKey.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_tag_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_keys.TagKey) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.short_name == 'short_name_value' - assert response.namespaced_name == 'namespaced_name_value' - assert response.description == 'description_value' - assert response.etag == 'etag_value' - - -def test_get_tag_key_rest_required_fields(request_type=tag_keys.GetTagKeyRequest): - transport_class = transports.TagKeysRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_tag_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_tag_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 = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tag_keys.TagKey() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = tag_keys.TagKey.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_tag_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_tag_key_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_tag_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagKeysRestInterceptor, "post_get_tag_key") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_get_tag_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.GetTagKeyRequest.pb(tag_keys.GetTagKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tag_keys.TagKey.to_json(tag_keys.TagKey()) - - request = tag_keys.GetTagKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_keys.TagKey() - - client.get_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.GetTagKeyRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagKeys/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_tag_key(request) - - -def test_get_tag_key_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_keys.TagKey() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'tagKeys/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_keys.TagKey.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_tag_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/v3/{name=tagKeys/*}" % client.transport._host, args[1]) - - -def test_get_tag_key_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.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_tag_key( - tag_keys.GetTagKeyRequest(), - name='name_value', - ) - - -def test_get_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.CreateTagKeyRequest, - dict, -]) -def test_create_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_key"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_tag_key(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_tag_key_rest_required_fields(request_type=tag_keys.CreateTagKeyRequest): - transport_class = transports.TagKeysRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tag_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()).create_tag_key._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = TagKeysClient( - 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_tag_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_tag_key_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_tag_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", )) & set(("tagKey", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_create_tag_key") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_create_tag_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.CreateTagKeyRequest.pb(tag_keys.CreateTagKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_keys.CreateTagKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.CreateTagKeyRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_key"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_tag_key(request) - - -def test_create_tag_key_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {} - - # get truthy value for each flattened field - mock_args = dict( - tag_key=tag_keys.TagKey(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_tag_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/v3/tagKeys" % client.transport._host, args[1]) - - -def test_create_tag_key_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.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_tag_key( - tag_keys.CreateTagKeyRequest(), - tag_key=tag_keys.TagKey(name='name_value'), - ) - - -def test_create_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.UpdateTagKeyRequest, - dict, -]) -def test_update_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'tag_key': {'name': 'tagKeys/sample1'}} - request_init["tag_key"] = {'name': 'tagKeys/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_tag_key(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_tag_key_rest_required_fields(request_type=tag_keys.UpdateTagKeyRequest): - transport_class = transports.TagKeysRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_tag_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_tag_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", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_tag_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_tag_key_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_tag_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("tagKey", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_update_tag_key") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_update_tag_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.UpdateTagKeyRequest.pb(tag_keys.UpdateTagKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_keys.UpdateTagKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.UpdateTagKeyRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'tag_key': {'name': 'tagKeys/sample1'}} - request_init["tag_key"] = {'name': 'tagKeys/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_tag_key(request) - - -def test_update_tag_key_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {'tag_key': {'name': 'tagKeys/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - tag_key=tag_keys.TagKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_tag_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/v3/{tag_key.name=tagKeys/*}" % client.transport._host, args[1]) - - -def test_update_tag_key_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.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_tag_key( - tag_keys.UpdateTagKeyRequest(), - tag_key=tag_keys.TagKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_keys.DeleteTagKeyRequest, - dict, -]) -def test_delete_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagKeys/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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_tag_key(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_tag_key_rest_required_fields(request_type=tag_keys.DeleteTagKeyRequest): - transport_class = transports.TagKeysRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_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()).delete_tag_key._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_tag_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_tag_key_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_tag_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_delete_tag_key") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_delete_tag_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.DeleteTagKeyRequest.pb(tag_keys.DeleteTagKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_keys.DeleteTagKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_key_rest_bad_request(transport: str = 'rest', request_type=tag_keys.DeleteTagKeyRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagKeys/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_tag_key(request) - - -def test_delete_tag_key_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'tagKeys/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_tag_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/v3/{name=tagKeys/*}" % client.transport._host, args[1]) - - -def test_delete_tag_key_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_tag_key( - tag_keys.DeleteTagKeyRequest(), - name='name_value', - ) - - -def test_delete_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagKeys/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.TagKeysRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagKeysRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagKeys/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'tagKeys/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=tagKeys/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagKeys/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.TagKeysRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagKeysRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagKeys/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'tagKeys/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=tagKeys/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagKeys/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.TagKeysRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.TagKeysRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagKeysRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.TagKeysRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagKeys/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'tagKeys/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=tagKeys/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagKeysClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagKeysClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagKeysClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagKeysClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TagKeysClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TagKeysGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TagKeysGrpcTransport, - transports.TagKeysGrpcAsyncIOTransport, - transports.TagKeysRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = TagKeysClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TagKeysGrpcTransport, - ) - -def test_tag_keys_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TagKeysTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_tag_keys_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.resourcemanager_v3.services.tag_keys.transports.TagKeysTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TagKeysTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_tag_keys', - 'get_tag_key', - 'create_tag_key', - 'update_tag_key', - 'delete_tag_key', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - 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_tag_keys_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.resourcemanager_v3.services.tag_keys.transports.TagKeysTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TagKeysTransport( - 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/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -def test_tag_keys_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.resourcemanager_v3.services.tag_keys.transports.TagKeysTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TagKeysTransport() - adc.assert_called_once() - - -def test_tag_keys_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) - TagKeysClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagKeysGrpcTransport, - transports.TagKeysGrpcAsyncIOTransport, - ], -) -def test_tag_keys_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/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagKeysGrpcTransport, - transports.TagKeysGrpcAsyncIOTransport, - transports.TagKeysRestTransport, - ], -) -def test_tag_keys_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.TagKeysGrpcTransport, grpc_helpers), - (transports.TagKeysGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_tag_keys_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( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TagKeysGrpcTransport, transports.TagKeysGrpcAsyncIOTransport]) -def test_tag_keys_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_tag_keys_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.TagKeysRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_tag_keys_rest_lro_client(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_tag_keys_host_no_port(transport_name): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_tag_keys_host_with_port(transport_name): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_tag_keys_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = TagKeysClient( - credentials=creds1, - transport=transport_name, - ) - client2 = TagKeysClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_tag_keys._session - session2 = client2.transport.list_tag_keys._session - assert session1 != session2 - session1 = client1.transport.get_tag_key._session - session2 = client2.transport.get_tag_key._session - assert session1 != session2 - session1 = client1.transport.create_tag_key._session - session2 = client2.transport.create_tag_key._session - assert session1 != session2 - session1 = client1.transport.update_tag_key._session - session2 = client2.transport.update_tag_key._session - assert session1 != session2 - session1 = client1.transport.delete_tag_key._session - session2 = client2.transport.delete_tag_key._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 -def test_tag_keys_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TagKeysGrpcTransport( - 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_tag_keys_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TagKeysGrpcAsyncIOTransport( - 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.TagKeysGrpcTransport, transports.TagKeysGrpcAsyncIOTransport]) -def test_tag_keys_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.TagKeysGrpcTransport, transports.TagKeysGrpcAsyncIOTransport]) -def test_tag_keys_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_tag_keys_grpc_lro_client(): - client = TagKeysClient( - 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_tag_keys_grpc_lro_async_client(): - client = TagKeysAsyncClient( - 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_tag_key_path(): - tag_key = "squid" - expected = "tagKeys/{tag_key}".format(tag_key=tag_key, ) - actual = TagKeysClient.tag_key_path(tag_key) - assert expected == actual - - -def test_parse_tag_key_path(): - expected = { - "tag_key": "clam", - } - path = TagKeysClient.tag_key_path(**expected) - - # Check that the path construction is reversible. - actual = TagKeysClient.parse_tag_key_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TagKeysClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = TagKeysClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TagKeysClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = TagKeysClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = TagKeysClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TagKeysClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TagKeysClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = TagKeysClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TagKeysClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = TagKeysClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = TagKeysClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TagKeysClient.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 = TagKeysClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = TagKeysClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TagKeysClient.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.TagKeysTransport, '_prep_wrapped_messages') as prep: - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TagKeysTransport, '_prep_wrapped_messages') as prep: - transport_class = TagKeysClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = TagKeysClient( - 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", [ - (TagKeysClient, transports.TagKeysGrpcTransport), - (TagKeysAsyncClient, transports.TagKeysGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py b/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py deleted file mode 100644 index a090fc1..0000000 --- a/owl-bot-staging/v3/tests/unit/gapic/resourcemanager_v3/test_tag_values.py +++ /dev/null @@ -1,5257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.resourcemanager_v3.services.tag_values import TagValuesAsyncClient -from google.cloud.resourcemanager_v3.services.tag_values import TagValuesClient -from google.cloud.resourcemanager_v3.services.tag_values import pagers -from google.cloud.resourcemanager_v3.services.tag_values import transports -from google.cloud.resourcemanager_v3.types import tag_values -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 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert TagValuesClient._get_default_mtls_endpoint(None) is None - assert TagValuesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TagValuesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TagValuesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TagValuesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TagValuesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (TagValuesClient, "grpc"), - (TagValuesAsyncClient, "grpc_asyncio"), - (TagValuesClient, "rest"), -]) -def test_tag_values_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.TagValuesGrpcTransport, "grpc"), - (transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TagValuesRestTransport, "rest"), -]) -def test_tag_values_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", [ - (TagValuesClient, "grpc"), - (TagValuesAsyncClient, "grpc_asyncio"), - (TagValuesClient, "rest"), -]) -def test_tag_values_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 == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudresourcemanager.googleapis.com' - ) - - -def test_tag_values_client_get_transport_class(): - transport = TagValuesClient.get_transport_class() - available_transports = [ - transports.TagValuesGrpcTransport, - transports.TagValuesRestTransport, - ] - assert transport in available_transports - - transport = TagValuesClient.get_transport_class("grpc") - assert transport == transports.TagValuesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TagValuesClient, transports.TagValuesGrpcTransport, "grpc"), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio"), - (TagValuesClient, transports.TagValuesRestTransport, "rest"), -]) -@mock.patch.object(TagValuesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesClient)) -@mock.patch.object(TagValuesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesAsyncClient)) -def test_tag_values_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(TagValuesClient, '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(TagValuesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", "true"), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", "false"), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TagValuesClient, transports.TagValuesRestTransport, "rest", "true"), - (TagValuesClient, transports.TagValuesRestTransport, "rest", "false"), -]) -@mock.patch.object(TagValuesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesClient)) -@mock.patch.object(TagValuesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_tag_values_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - TagValuesClient, TagValuesAsyncClient -]) -@mock.patch.object(TagValuesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesClient)) -@mock.patch.object(TagValuesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TagValuesAsyncClient)) -def test_tag_values_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TagValuesClient, transports.TagValuesGrpcTransport, "grpc"), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio"), - (TagValuesClient, transports.TagValuesRestTransport, "rest"), -]) -def test_tag_values_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", grpc_helpers), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TagValuesClient, transports.TagValuesRestTransport, "rest", None), -]) -def test_tag_values_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_tag_values_client_client_options_from_dict(): - with mock.patch('google.cloud.resourcemanager_v3.services.tag_values.transports.TagValuesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TagValuesClient( - 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", [ - (TagValuesClient, transports.TagValuesGrpcTransport, "grpc", grpc_helpers), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_tag_values_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=None, - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.ListTagValuesRequest, - dict, -]) -def test_list_tag_values(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_values), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_values.ListTagValuesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_tag_values(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.ListTagValuesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagValuesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tag_values_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_values), - '__call__') as call: - client.list_tag_values() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.ListTagValuesRequest() - -@pytest.mark.asyncio -async def test_list_tag_values_async(transport: str = 'grpc_asyncio', request_type=tag_values.ListTagValuesRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_values), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_values.ListTagValuesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_tag_values(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.ListTagValuesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagValuesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_tag_values_async_from_dict(): - await test_list_tag_values_async(request_type=dict) - - -def test_list_tag_values_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_values), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_values.ListTagValuesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tag_values( - 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_tag_values_flattened_error(): - client = TagValuesClient( - credentials=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_tag_values( - tag_values.ListTagValuesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tag_values_flattened_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_values), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_values.ListTagValuesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_values.ListTagValuesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tag_values( - 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_tag_values_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_tag_values( - tag_values.ListTagValuesRequest(), - parent='parent_value', - ) - - -def test_list_tag_values_pager(transport_name: str = "grpc"): - client = TagValuesClient( - 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_tag_values), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - tag_values.TagValue(), - ], - next_page_token='abc', - ), - tag_values.ListTagValuesResponse( - tag_values=[], - next_page_token='def', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - ], - next_page_token='ghi', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_tag_values(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_values.TagValue) - for i in results) -def test_list_tag_values_pages(transport_name: str = "grpc"): - client = TagValuesClient( - 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_tag_values), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - tag_values.TagValue(), - ], - next_page_token='abc', - ), - tag_values.ListTagValuesResponse( - tag_values=[], - next_page_token='def', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - ], - next_page_token='ghi', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tag_values(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_tag_values_async_pager(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_values), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - tag_values.TagValue(), - ], - next_page_token='abc', - ), - tag_values.ListTagValuesResponse( - tag_values=[], - next_page_token='def', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - ], - next_page_token='ghi', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tag_values(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, tag_values.TagValue) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tag_values_async_pages(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_values), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - tag_values.TagValue(), - ], - next_page_token='abc', - ), - tag_values.ListTagValuesResponse( - tag_values=[], - next_page_token='def', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - ], - next_page_token='ghi', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_tag_values(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - tag_values.GetTagValueRequest, - dict, -]) -def test_get_tag_value(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_values.TagValue( - name='name_value', - parent='parent_value', - short_name='short_name_value', - namespaced_name='namespaced_name_value', - description='description_value', - etag='etag_value', - ) - response = client.get_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_values.TagValue) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.short_name == 'short_name_value' - assert response.namespaced_name == 'namespaced_name_value' - assert response.description == 'description_value' - assert response.etag == 'etag_value' - - -def test_get_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_value), - '__call__') as call: - client.get_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetTagValueRequest() - -@pytest.mark.asyncio -async def test_get_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.GetTagValueRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tag_values.TagValue( - name='name_value', - parent='parent_value', - short_name='short_name_value', - namespaced_name='namespaced_name_value', - description='description_value', - etag='etag_value', - )) - response = await client.get_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_values.TagValue) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.short_name == 'short_name_value' - assert response.namespaced_name == 'namespaced_name_value' - assert response.description == 'description_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_tag_value_async_from_dict(): - await test_get_tag_value_async(request_type=dict) - - -def test_get_tag_value_field_headers(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_values.GetTagValueRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_value), - '__call__') as call: - call.return_value = tag_values.TagValue() - client.get_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_tag_value_field_headers_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_values.GetTagValueRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_value), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_values.TagValue()) - await client.get_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_tag_value_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_values.TagValue() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_tag_value( - 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_tag_value_flattened_error(): - client = TagValuesClient( - credentials=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_tag_value( - tag_values.GetTagValueRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_tag_value_flattened_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tag_values.TagValue() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tag_values.TagValue()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_tag_value( - 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_tag_value_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_tag_value( - tag_values.GetTagValueRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.CreateTagValueRequest, - dict, -]) -def test_create_tag_value(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.CreateTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_value), - '__call__') as call: - client.create_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.CreateTagValueRequest() - -@pytest.mark.asyncio -async def test_create_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.CreateTagValueRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_value), - '__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_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.CreateTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_tag_value_async_from_dict(): - await test_create_tag_value_async(request_type=dict) - - -def test_create_tag_value_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_value), - '__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_tag_value( - tag_value=tag_values.TagValue(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].tag_value - mock_val = tag_values.TagValue(name='name_value') - assert arg == mock_val - - -def test_create_tag_value_flattened_error(): - client = TagValuesClient( - credentials=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_tag_value( - tag_values.CreateTagValueRequest(), - tag_value=tag_values.TagValue(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_tag_value_flattened_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_value), - '__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_tag_value( - tag_value=tag_values.TagValue(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].tag_value - mock_val = tag_values.TagValue(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_tag_value_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_tag_value( - tag_values.CreateTagValueRequest(), - tag_value=tag_values.TagValue(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.UpdateTagValueRequest, - dict, -]) -def test_update_tag_value(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.UpdateTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_value), - '__call__') as call: - client.update_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.UpdateTagValueRequest() - -@pytest.mark.asyncio -async def test_update_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.UpdateTagValueRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.UpdateTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_tag_value_async_from_dict(): - await test_update_tag_value_async(request_type=dict) - - -def test_update_tag_value_field_headers(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_values.UpdateTagValueRequest() - - request.tag_value.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_value), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tag_value.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_tag_value_field_headers_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_values.UpdateTagValueRequest() - - request.tag_value.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_value), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'tag_value.name=name_value', - ) in kw['metadata'] - - -def test_update_tag_value_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_tag_value( - tag_value=tag_values.TagValue(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].tag_value - mock_val = tag_values.TagValue(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_tag_value_flattened_error(): - client = TagValuesClient( - credentials=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_tag_value( - tag_values.UpdateTagValueRequest(), - tag_value=tag_values.TagValue(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_tag_value_flattened_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_tag_value( - tag_value=tag_values.TagValue(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].tag_value - mock_val = tag_values.TagValue(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_tag_value_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_tag_value( - tag_values.UpdateTagValueRequest(), - tag_value=tag_values.TagValue(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.DeleteTagValueRequest, - dict, -]) -def test_delete_tag_value(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.DeleteTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - client.delete_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.DeleteTagValueRequest() - -@pytest.mark.asyncio -async def test_delete_tag_value_async(transport: str = 'grpc_asyncio', request_type=tag_values.DeleteTagValueRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.DeleteTagValueRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_tag_value_async_from_dict(): - await test_delete_tag_value_async(request_type=dict) - - -def test_delete_tag_value_field_headers(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_values.DeleteTagValueRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_tag_value_field_headers_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = tag_values.DeleteTagValueRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_tag_value(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_tag_value_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_tag_value( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_tag_value_flattened_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_tag_value( - tag_values.DeleteTagValueRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_tag_value_flattened_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_value), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_tag_value( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_tag_value_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_tag_value( - tag_values.DeleteTagValueRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = TagValuesClient( - 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() - - -def test_get_iam_policy_flattened(): - client = TagValuesClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = TagValuesClient( - credentials=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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = TagValuesAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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( - 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) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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) - _, args, _ = call.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_foreign(): - client = TagValuesClient( - 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), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = TagValuesClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = TagValuesAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # 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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = TagValuesClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = TagValuesClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = TagValuesAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.ListTagValuesRequest, - dict, -]) -def test_list_tag_values_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_values.ListTagValuesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_values.ListTagValuesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tag_values(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagValuesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_tag_values_rest_required_fields(request_type=tag_values.ListTagValuesRequest): - transport_class = transports.TagValuesRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "parent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_values._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "parent" in jsonified_request - assert jsonified_request["parent"] == request_init["parent"] - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tag_values._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "parent", )) - 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 = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tag_values.ListTagValuesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = tag_values.ListTagValuesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tag_values(request) - - expected_params = [ - ( - "parent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tag_values_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tag_values._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "parent", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_values_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagValuesRestInterceptor, "post_list_tag_values") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_list_tag_values") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.ListTagValuesRequest.pb(tag_values.ListTagValuesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tag_values.ListTagValuesResponse.to_json(tag_values.ListTagValuesResponse()) - - request = tag_values.ListTagValuesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_values.ListTagValuesResponse() - - client.list_tag_values(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_values_rest_bad_request(transport: str = 'rest', request_type=tag_values.ListTagValuesRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_tag_values(request) - - -def test_list_tag_values_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_values.ListTagValuesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_values.ListTagValuesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tag_values(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/tagValues" % client.transport._host, args[1]) - - -def test_list_tag_values_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.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_tag_values( - tag_values.ListTagValuesRequest(), - parent='parent_value', - ) - - -def test_list_tag_values_rest_pager(transport: str = 'rest'): - client = TagValuesClient( - 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 = ( - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - tag_values.TagValue(), - ], - next_page_token='abc', - ), - tag_values.ListTagValuesResponse( - tag_values=[], - next_page_token='def', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - ], - next_page_token='ghi', - ), - tag_values.ListTagValuesResponse( - tag_values=[ - tag_values.TagValue(), - tag_values.TagValue(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(tag_values.ListTagValuesResponse.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 = {} - - pager = client.list_tag_values(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_values.TagValue) - for i in results) - - pages = list(client.list_tag_values(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - tag_values.GetTagValueRequest, - dict, -]) -def test_get_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagValues/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 = tag_values.TagValue( - name='name_value', - parent='parent_value', - short_name='short_name_value', - namespaced_name='namespaced_name_value', - description='description_value', - etag='etag_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_values.TagValue.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_tag_value(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_values.TagValue) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.short_name == 'short_name_value' - assert response.namespaced_name == 'namespaced_name_value' - assert response.description == 'description_value' - assert response.etag == 'etag_value' - - -def test_get_tag_value_rest_required_fields(request_type=tag_values.GetTagValueRequest): - transport_class = transports.TagValuesRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_tag_value._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_tag_value._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 = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tag_values.TagValue() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = tag_values.TagValue.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_tag_value(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_tag_value_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_tag_value._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagValuesRestInterceptor, "post_get_tag_value") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_get_tag_value") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.GetTagValueRequest.pb(tag_values.GetTagValueRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tag_values.TagValue.to_json(tag_values.TagValue()) - - request = tag_values.GetTagValueRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_values.TagValue() - - client.get_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.GetTagValueRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagValues/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_tag_value(request) - - -def test_get_tag_value_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tag_values.TagValue() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'tagValues/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = tag_values.TagValue.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_tag_value(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=tagValues/*}" % client.transport._host, args[1]) - - -def test_get_tag_value_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.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_tag_value( - tag_values.GetTagValueRequest(), - name='name_value', - ) - - -def test_get_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.CreateTagValueRequest, - dict, -]) -def test_create_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_value"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_tag_value(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_tag_value_rest_required_fields(request_type=tag_values.CreateTagValueRequest): - transport_class = transports.TagValuesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_tag_value._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()).create_tag_value._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = TagValuesClient( - 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_tag_value(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_tag_value_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_tag_value._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", )) & set(("tagValue", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_create_tag_value") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_create_tag_value") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.CreateTagValueRequest.pb(tag_values.CreateTagValueRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_values.CreateTagValueRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.CreateTagValueRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_value"] = {'name': 'name_value', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_tag_value(request) - - -def test_create_tag_value_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {} - - # get truthy value for each flattened field - mock_args = dict( - tag_value=tag_values.TagValue(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_tag_value(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/tagValues" % client.transport._host, args[1]) - - -def test_create_tag_value_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.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_tag_value( - tag_values.CreateTagValueRequest(), - tag_value=tag_values.TagValue(name='name_value'), - ) - - -def test_create_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.UpdateTagValueRequest, - dict, -]) -def test_update_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'tag_value': {'name': 'tagValues/sample1'}} - request_init["tag_value"] = {'name': 'tagValues/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_tag_value(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_tag_value_rest_required_fields(request_type=tag_values.UpdateTagValueRequest): - transport_class = transports.TagValuesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_tag_value._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_tag_value._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_tag_value(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_tag_value_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_tag_value._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", "validateOnly", )) & set(("tagValue", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_update_tag_value") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_update_tag_value") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.UpdateTagValueRequest.pb(tag_values.UpdateTagValueRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_values.UpdateTagValueRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.UpdateTagValueRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'tag_value': {'name': 'tagValues/sample1'}} - request_init["tag_value"] = {'name': 'tagValues/sample1', 'parent': 'parent_value', 'short_name': 'short_name_value', 'namespaced_name': 'namespaced_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'etag': 'etag_value'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_tag_value(request) - - -def test_update_tag_value_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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 = {'tag_value': {'name': 'tagValues/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - tag_value=tag_values.TagValue(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_tag_value(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{tag_value.name=tagValues/*}" % client.transport._host, args[1]) - - -def test_update_tag_value_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.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_tag_value( - tag_values.UpdateTagValueRequest(), - tag_value=tag_values.TagValue(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - tag_values.DeleteTagValueRequest, - dict, -]) -def test_delete_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagValues/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 = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_tag_value(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_tag_value_rest_required_fields(request_type=tag_values.DeleteTagValueRequest): - transport_class = transports.TagValuesRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_value._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_tag_value._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_tag_value(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_tag_value_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_tag_value._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_delete_tag_value") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_delete_tag_value") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.DeleteTagValueRequest.pb(tag_values.DeleteTagValueRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = tag_values.DeleteTagValueRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_value(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_value_rest_bad_request(transport: str = 'rest', request_type=tag_values.DeleteTagValueRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'tagValues/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_tag_value(request) - - -def test_delete_tag_value_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'tagValues/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_tag_value(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{name=tagValues/*}" % client.transport._host, args[1]) - - -def test_delete_tag_value_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_tag_value( - tag_values.DeleteTagValueRequest(), - name='name_value', - ) - - -def test_delete_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagValues/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.TagValuesRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagValuesRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagValues/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'tagValues/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=tagValues/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagValues/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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(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_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.TagValuesRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagValuesRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagValues/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'tagValues/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_iam_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=tagValues/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagValues/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(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_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.TagValuesRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = 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 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.TagValuesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.TagValuesRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.TagValuesRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'tagValues/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'tagValues/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.test_iam_permissions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v3/{resource=tagValues/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagValuesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagValuesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagValuesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagValuesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TagValuesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TagValuesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TagValuesGrpcTransport, - transports.TagValuesGrpcAsyncIOTransport, - transports.TagValuesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = TagValuesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TagValuesGrpcTransport, - ) - -def test_tag_values_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TagValuesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_tag_values_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.resourcemanager_v3.services.tag_values.transports.TagValuesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TagValuesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_tag_values', - 'get_tag_value', - 'create_tag_value', - 'update_tag_value', - 'delete_tag_value', - 'get_iam_policy', - 'set_iam_policy', - 'test_iam_permissions', - ) - 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_tag_values_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.resourcemanager_v3.services.tag_values.transports.TagValuesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TagValuesTransport( - 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/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -def test_tag_values_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.resourcemanager_v3.services.tag_values.transports.TagValuesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TagValuesTransport() - adc.assert_called_once() - - -def test_tag_values_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) - TagValuesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagValuesGrpcTransport, - transports.TagValuesGrpcAsyncIOTransport, - ], -) -def test_tag_values_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/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagValuesGrpcTransport, - transports.TagValuesGrpcAsyncIOTransport, - transports.TagValuesRestTransport, - ], -) -def test_tag_values_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.TagValuesGrpcTransport, grpc_helpers), - (transports.TagValuesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_tag_values_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( - "cloudresourcemanager.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/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="cloudresourcemanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TagValuesGrpcTransport, transports.TagValuesGrpcAsyncIOTransport]) -def test_tag_values_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_tag_values_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.TagValuesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_tag_values_rest_lro_client(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_tag_values_host_no_port(transport_name): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_tag_values_host_with_port(transport_name): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudresourcemanager.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudresourcemanager.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudresourcemanager.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_tag_values_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = TagValuesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = TagValuesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_tag_values._session - session2 = client2.transport.list_tag_values._session - assert session1 != session2 - session1 = client1.transport.get_tag_value._session - session2 = client2.transport.get_tag_value._session - assert session1 != session2 - session1 = client1.transport.create_tag_value._session - session2 = client2.transport.create_tag_value._session - assert session1 != session2 - session1 = client1.transport.update_tag_value._session - session2 = client2.transport.update_tag_value._session - assert session1 != session2 - session1 = client1.transport.delete_tag_value._session - session2 = client2.transport.delete_tag_value._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 -def test_tag_values_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TagValuesGrpcTransport( - 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_tag_values_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TagValuesGrpcAsyncIOTransport( - 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.TagValuesGrpcTransport, transports.TagValuesGrpcAsyncIOTransport]) -def test_tag_values_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.TagValuesGrpcTransport, transports.TagValuesGrpcAsyncIOTransport]) -def test_tag_values_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_tag_values_grpc_lro_client(): - client = TagValuesClient( - 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_tag_values_grpc_lro_async_client(): - client = TagValuesAsyncClient( - 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_tag_value_path(): - tag_value = "squid" - expected = "tagValues/{tag_value}".format(tag_value=tag_value, ) - actual = TagValuesClient.tag_value_path(tag_value) - assert expected == actual - - -def test_parse_tag_value_path(): - expected = { - "tag_value": "clam", - } - path = TagValuesClient.tag_value_path(**expected) - - # Check that the path construction is reversible. - actual = TagValuesClient.parse_tag_value_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TagValuesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = TagValuesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TagValuesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = TagValuesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = TagValuesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TagValuesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TagValuesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = TagValuesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TagValuesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = TagValuesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = TagValuesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TagValuesClient.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 = TagValuesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = TagValuesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TagValuesClient.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.TagValuesTransport, '_prep_wrapped_messages') as prep: - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TagValuesTransport, '_prep_wrapped_messages') as prep: - transport_class = TagValuesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = TagValuesClient( - 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", [ - (TagValuesClient, transports.TagValuesGrpcTransport), - (TagValuesAsyncClient, transports.TagValuesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - )